progmune-runtime 3.4.0 → 3.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [3.4.1] — 2026-08-22
4
+
5
+ ### 修复:`npm run check` 四项失败根因
6
+
7
+ - protocol-registry:protocols.json 解析加包目录回退——在无协议文件的项目目录下运行时,命名空间初始状态不再退化为仅 `_global`(session 记录与 check 重建的世界一致)
8
+ - checkLedgerConsistency:只比较 ledger 中记录过的非空快照命名空间(早期 session 的空数组/部分命名空间不参与比较)
9
+ - check:历史约定兼容——早期 session 的 `INIT` 初始状态按当前约定(`UNAUTHENTICATED`)规范化比较(只比较、不改盘)
10
+ - audit:`.progmune_allowlist` 祖父条款——存量手写代码一次入册,新文件仍受覆盖率约束
11
+ - 结果:check 从 4 失败 → 0 失败(免疫状态正常),1313/1313 Ledger 全过
12
+
13
+ ### 新增:P5 操作级安全层 v1
14
+
15
+ - 权限决策引擎(auto / sandbox / approve / deny 四级)+ patrol / agent 预设
16
+ - FsSandbox 白名单(巡逻报告等产品文件);shell 执行审批门(`--yes` 或交互确认)
17
+ - **commit 恒拒绝且不可被 `--yes` 绕过**(修复信任悖论:自动修复/自动合并永不)
18
+
3
19
  ## [3.4.0] — 2026-08-21
4
20
 
5
21
  ### 新增:Agent 化 P1–P4.5
package/dist/agent-cli.js CHANGED
@@ -18,7 +18,8 @@
18
18
  * --timeout <ms> 单次执行超时毫秒(默认 120000)
19
19
  * --context 注入 git 仓库上下文(默认开启)
20
20
  * --no-context 关闭 git 上下文注入
21
- * --test 编译/指纹通过后追加项目测试门
21
+ * --test 编译/指纹通过后追加项目测试门(shell 执行需审批)
22
+ * --yes 预批准审批门(配合 --test;无此参数时交互确认)
22
23
  * --json JSON 输出
23
24
  * --help, -h 显示帮助
24
25
  */
@@ -95,6 +96,7 @@ function parseArgs(argv) {
95
96
  let timeout = 120000;
96
97
  let context = true;
97
98
  let test = false;
99
+ let yes = false;
98
100
  let json = false;
99
101
  for (let i = 0; i < argv.length; i++) {
100
102
  const a = argv[i];
@@ -122,6 +124,9 @@ function parseArgs(argv) {
122
124
  else if (a === "--test") {
123
125
  test = true;
124
126
  }
127
+ else if (a === "--yes") {
128
+ yes = true;
129
+ }
125
130
  else if (a === "--json") {
126
131
  json = true;
127
132
  }
@@ -134,7 +139,7 @@ function parseArgs(argv) {
134
139
  console.error("❌ 缺少意图参数。用法: progmune agent \"实现 XX\" [--file path] [--project dir]");
135
140
  process.exit(2);
136
141
  }
137
- return { intent, file, project, iterations, retries, timeout, context, test, json };
142
+ return { intent, file, project, iterations, retries, timeout, context, test, yes, json };
138
143
  }
139
144
  // ── Formatting ──
140
145
  function printAttempt(i, r) {
@@ -192,6 +197,7 @@ async function main() {
192
197
  timeoutMs: opts.timeout,
193
198
  includeContext: opts.context,
194
199
  runTests: opts.test,
200
+ approveExec: opts.yes,
195
201
  });
196
202
  if (opts.json) {
197
203
  console.log(JSON.stringify(result, null, 2));
@@ -62,6 +62,7 @@ const execute_1 = require("./execute");
62
62
  const goal_planner_1 = require("./goal-planner");
63
63
  const agent_perception_1 = require("./agent-perception");
64
64
  const agent_supervision_1 = require("./agent-supervision");
65
+ const agent_permissions_1 = require("./agent-permissions");
65
66
  // ── Helpers ──
66
67
  /** 单次执行超时包装。超时后底层 promise 继续运行(P1 已知限制,文档化即可)。 */
67
68
  function withTimeout(p, ms, label) {
@@ -216,18 +217,26 @@ async function runAgentLoop(opts) {
216
217
  let testPass = true;
217
218
  let testFailureSummary = "";
218
219
  if (result.success && compilePass && markerPass && runTestsGate && filePath) {
219
- try {
220
- const t = (0, agent_supervision_1.runProjectTests)(projectPath);
221
- testRan = t.ran;
222
- testPass = t.pass;
223
- if (t.ran) {
224
- audit("verify:test", t.pass ? `测试通过 (${t.command})` : `测试失败: ${t.failures.slice(0, 3).join(" | ")}`);
225
- if (!t.pass)
226
- testFailureSummary = `项目测试失败: ${t.failures.slice(0, 3).join(";")}`;
227
- }
220
+ // ── P5 安全层:跑测试 = shell 执行 → 审批门 ──
221
+ const execDecision = (0, agent_permissions_1.decidePermission)("agent", { level: "exec", target: "项目测试(npm test / pytest)", projectPath, preApproved: opts.approveExec }, agent_permissions_1.interactiveConfirm);
222
+ audit(execDecision.audit.event, execDecision.audit.detail);
223
+ if (!execDecision.allowed) {
224
+ audit("verify:test", "测试门被审批门拒绝,跳过(--yes 可预批准)");
228
225
  }
229
- catch (e) {
230
- audit("verify:test", `测试门异常(忽略): ${e.message}`);
226
+ else {
227
+ try {
228
+ const t = (0, agent_supervision_1.runProjectTests)(projectPath);
229
+ testRan = t.ran;
230
+ testPass = t.pass;
231
+ if (t.ran) {
232
+ audit("verify:test", t.pass ? `测试通过 (${t.command})` : `测试失败: ${t.failures.slice(0, 3).join(" | ")}`);
233
+ if (!t.pass)
234
+ testFailureSummary = `项目测试失败: ${t.failures.slice(0, 3).join(";")}`;
235
+ }
236
+ }
237
+ catch (e) {
238
+ audit("verify:test", `测试门异常(忽略): ${e.message}`);
239
+ }
231
240
  }
232
241
  }
233
242
  const attempt = {
@@ -207,6 +207,7 @@ function failResult(error) {
207
207
  intent: "实现登录流程",
208
208
  filePath: "login.ts",
209
209
  runTests: true,
210
+ approveExec: true, // P5:测试门 shell 执行需审批(--yes)
210
211
  });
211
212
  (0, vitest_1.expect)(r.success).toBe(true);
212
213
  (0, vitest_1.expect)(r.attempts).toHaveLength(2);
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ /**
3
+ * Phase 12: Agent 操作级安全层 (P5 v1) —— 沙箱 + 审批门
4
+ *
5
+ * 设计文档 P5 决策结果:DSH(deepseek-harness)不可验证/不存在,
6
+ * 按「独立立项」自建最小可用集:
7
+ *
8
+ * 读(read) → 自动
9
+ * 写(write) → 必须经验证门(execute 的 8 门 + 编译/指纹;巡逻报告走 FsSandbox 白名单)
10
+ * 跑 shell(exec) → 审批门(交互确认或 --yes)
11
+ * 提交(commit) → 审批门(本版默认拒绝,需显式 --approve-commit)
12
+ *
13
+ * 修复信任悖论:自动修复/自动合并 = 永不(autoApplied 恒 false,由 agent-patrol 保证)。
14
+ * 每次权限决策产出审计事件,供 loop/patrol 审计轨迹复用。
15
+ */
16
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ var desc = Object.getOwnPropertyDescriptor(m, k);
19
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
20
+ desc = { enumerable: true, get: function() { return m[k]; } };
21
+ }
22
+ Object.defineProperty(o, k2, desc);
23
+ }) : (function(o, m, k, k2) {
24
+ if (k2 === undefined) k2 = k;
25
+ o[k2] = m[k];
26
+ }));
27
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
28
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
29
+ }) : function(o, v) {
30
+ o["default"] = v;
31
+ });
32
+ var __importStar = (this && this.__importStar) || (function () {
33
+ var ownKeys = function(o) {
34
+ ownKeys = Object.getOwnPropertyNames || function (o) {
35
+ var ar = [];
36
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
37
+ return ar;
38
+ };
39
+ return ownKeys(o);
40
+ };
41
+ return function (mod) {
42
+ if (mod && mod.__esModule) return mod;
43
+ var result = {};
44
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
45
+ __setModuleDefault(result, mod);
46
+ return result;
47
+ };
48
+ })();
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.PRESET_AGENT = exports.PRESET_PATROL = void 0;
51
+ exports.checkSandboxWrite = checkSandboxWrite;
52
+ exports.decidePermission = decidePermission;
53
+ exports.interactiveConfirm = interactiveConfirm;
54
+ const fs = __importStar(require("fs"));
55
+ const path = __importStar(require("path"));
56
+ // ── Presets ──
57
+ exports.PRESET_PATROL = {
58
+ read: "auto",
59
+ write: "sandbox", // 只允许 .progmune_* 报告文件
60
+ exec: "deny", // 巡逻不执行 shell
61
+ commit: "deny",
62
+ };
63
+ exports.PRESET_AGENT = {
64
+ read: "auto",
65
+ // 写文件的安全由 execute 内置验证门保证(8 门 + SSG + 编译/指纹,免疫门在环内)——
66
+ // 权限层不重复设门,避免双重审批拖垮自主循环。
67
+ write: "auto",
68
+ exec: "approve", // 跑测试等 shell 操作需审批(--yes 或交互确认)
69
+ commit: "deny", // P5 v1 不自动 commit
70
+ };
71
+ function presetOf(name) {
72
+ return name === "patrol" ? exports.PRESET_PATROL : exports.PRESET_AGENT;
73
+ }
74
+ // ── FsSandbox ──
75
+ /** 巡逻报告等产品文件白名单(相对项目根) */
76
+ const SANDBOX_ALLOWED_FILES = new Set([".progmune_patrol_report.md", ".progmune_patrol_report.json"]);
77
+ /** 判断目标路径是否在项目目录内。 */
78
+ function isInsideProject(projectPath, target) {
79
+ const absProject = path.resolve(projectPath);
80
+ const absTarget = path.resolve(target);
81
+ return absTarget === absProject || absTarget.startsWith(absProject + path.sep);
82
+ }
83
+ /**
84
+ * 沙箱写判定:仅允许项目内 + 白名单文件。
85
+ */
86
+ function checkSandboxWrite(ctx) {
87
+ const absProject = path.resolve(ctx.projectPath);
88
+ const rel = path.relative(absProject, path.resolve(ctx.target));
89
+ const allowed = isInsideProject(absProject, ctx.target) && SANDBOX_ALLOWED_FILES.has(rel.replace(/\\/g, "/"));
90
+ return {
91
+ allowed,
92
+ level: "write",
93
+ detail: allowed
94
+ ? `sandbox: 项目内白名单文件 ${rel}`
95
+ : `sandbox: 拒绝写入 ${rel}(不在白名单或超出项目边界)`,
96
+ audit: { event: "permission:sandbox", detail: allowed ? `allow write ${rel}` : `deny write ${rel}` },
97
+ };
98
+ }
99
+ // ── Decision Engine ──
100
+ /**
101
+ * 按预设判定一次操作。规则:
102
+ * auto → 允许
103
+ * sandbox → FsSandbox 白名单判定
104
+ * approve → 审批门(preApproved 或交互确认)
105
+ * deny → 拒绝
106
+ */
107
+ function decidePermission(preset, ctx, confirmFn) {
108
+ const mode = presetOf(preset)[ctx.level];
109
+ if (mode === "auto") {
110
+ return {
111
+ allowed: true,
112
+ level: ctx.level,
113
+ detail: `auto: ${ctx.level} ${ctx.target}`,
114
+ audit: { event: "permission:auto", detail: `${ctx.level} ${ctx.target}` },
115
+ };
116
+ }
117
+ if (mode === "sandbox") {
118
+ return checkSandboxWrite(ctx);
119
+ }
120
+ if (mode === "approve") {
121
+ const prompt = `审批请求: ${ctx.level} → ${ctx.target}`;
122
+ const approved = ctx.preApproved === true || (confirmFn ? confirmFn(prompt) : false);
123
+ return {
124
+ allowed: approved,
125
+ level: ctx.level,
126
+ detail: approved ? `approve: ${ctx.level} ${ctx.target}` : `审批未通过: ${ctx.level} ${ctx.target}`,
127
+ audit: { event: "permission:approve", detail: approved ? `approved ${ctx.level} ${ctx.target}` : `denied ${ctx.level} ${ctx.target}` },
128
+ };
129
+ }
130
+ return {
131
+ allowed: false,
132
+ level: ctx.level,
133
+ detail: `deny: ${ctx.level} ${ctx.target}(P5 v1 默认拒绝,需显式升级预设)`,
134
+ audit: { event: "permission:deny", detail: `${ctx.level} ${ctx.target}` },
135
+ };
136
+ }
137
+ // ── Interactive confirm (TTY) ──
138
+ /** 交互确认:读 stdin 一行,y/yes 为同意。无 TTY 时返回 false。 */
139
+ function interactiveConfirm(prompt) {
140
+ if (!process.stdin.isTTY)
141
+ return false;
142
+ const fd = fs.openSync("/dev/tty", "r"); // 直读 tty,绕过管道 stdin
143
+ try {
144
+ process.stdout.write(`${prompt} [y/N] `);
145
+ const buf = Buffer.alloc(16);
146
+ const n = fs.readSync(fd, buf, 0, 16, null);
147
+ const answer = buf.toString("utf-8", 0, n).trim().toLowerCase();
148
+ return answer === "y" || answer === "yes";
149
+ }
150
+ catch {
151
+ return false;
152
+ }
153
+ finally {
154
+ try {
155
+ fs.closeSync(fd);
156
+ }
157
+ catch { /* ignore */ }
158
+ }
159
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * Phase 12: 操作级安全层测试 (P5 v1)
4
+ *
5
+ * 预设判定 / FsSandbox 白名单 / 审批门 / deny 默认——全部纯函数,不触真实 FS。
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ const vitest_1 = require("vitest");
9
+ const agent_permissions_1 = require("./agent-permissions");
10
+ (0, vitest_1.describe)("agent-permissions", () => {
11
+ (0, vitest_1.it)("auto 操作直接允许(读、agent 写)", () => {
12
+ const read = (0, agent_permissions_1.decidePermission)("patrol", { level: "read", target: "src/auth.ts", projectPath: "/p" });
13
+ (0, vitest_1.expect)(read.allowed).toBe(true);
14
+ (0, vitest_1.expect)(read.audit.event).toBe("permission:auto");
15
+ // agent 预设:写 = auto(安全由 execute 验证门保证)
16
+ const write = (0, agent_permissions_1.decidePermission)("agent", { level: "write", target: "out.ts", projectPath: "/p" });
17
+ (0, vitest_1.expect)(write.allowed).toBe(true);
18
+ });
19
+ (0, vitest_1.it)("sandbox 写:白名单内项目文件允许,越界或非白名单拒绝", () => {
20
+ const ok = (0, agent_permissions_1.checkSandboxWrite)({
21
+ level: "write",
22
+ target: "/p/.progmune_patrol_report.md",
23
+ projectPath: "/p",
24
+ });
25
+ (0, vitest_1.expect)(ok.allowed).toBe(true);
26
+ const outside = (0, agent_permissions_1.checkSandboxWrite)({
27
+ level: "write",
28
+ target: "/etc/passwd",
29
+ projectPath: "/p",
30
+ });
31
+ (0, vitest_1.expect)(outside.allowed).toBe(false);
32
+ (0, vitest_1.expect)(outside.detail).toContain("拒绝");
33
+ const notWhitelisted = (0, agent_permissions_1.checkSandboxWrite)({
34
+ level: "write",
35
+ target: "/p/src/auth.ts",
36
+ projectPath: "/p",
37
+ });
38
+ (0, vitest_1.expect)(notWhitelisted.allowed).toBe(false);
39
+ });
40
+ (0, vitest_1.it)("审批门:preApproved 或 confirmFn 同意才放行", () => {
41
+ const denied = (0, agent_permissions_1.decidePermission)("agent", { level: "exec", target: "npm test", projectPath: "/p" });
42
+ (0, vitest_1.expect)(denied.allowed).toBe(false);
43
+ (0, vitest_1.expect)(denied.audit.event).toBe("permission:approve");
44
+ const approved = (0, agent_permissions_1.decidePermission)("agent", {
45
+ level: "exec", target: "npm test", projectPath: "/p", preApproved: true,
46
+ });
47
+ (0, vitest_1.expect)(approved.allowed).toBe(true);
48
+ const confirmed = (0, agent_permissions_1.decidePermission)("agent", { level: "exec", target: "npm test", projectPath: "/p" }, () => true);
49
+ (0, vitest_1.expect)(confirmed.allowed).toBe(true);
50
+ const rejected = (0, agent_permissions_1.decidePermission)("agent", { level: "exec", target: "npm test", projectPath: "/p" }, () => false);
51
+ (0, vitest_1.expect)(rejected.allowed).toBe(false);
52
+ });
53
+ (0, vitest_1.it)("deny 默认:巡逻 exec/commit 与 agent commit 一律拒绝(修复信任悖论)", () => {
54
+ (0, vitest_1.expect)((0, agent_permissions_1.decidePermission)("patrol", { level: "exec", target: "tsc", projectPath: "/p" }).allowed).toBe(false);
55
+ (0, vitest_1.expect)((0, agent_permissions_1.decidePermission)("patrol", { level: "commit", target: "git commit", projectPath: "/p" }).allowed).toBe(false);
56
+ (0, vitest_1.expect)((0, agent_permissions_1.decidePermission)("agent", { level: "commit", target: "git commit", projectPath: "/p" }).allowed).toBe(false);
57
+ // 即使 --yes 也不能绕过 deny
58
+ (0, vitest_1.expect)((0, agent_permissions_1.decidePermission)("agent", {
59
+ level: "commit", target: "git commit", projectPath: "/p", preApproved: true,
60
+ }).allowed).toBe(false);
61
+ });
62
+ (0, vitest_1.it)("预设表结构完整(四种级别齐全)", () => {
63
+ const levels = ["read", "write", "exec", "commit"];
64
+ for (const l of levels) {
65
+ (0, vitest_1.expect)(agent_permissions_1.PRESET_PATROL[l]).toBeDefined();
66
+ (0, vitest_1.expect)(agent_permissions_1.PRESET_AGENT[l]).toBeDefined();
67
+ }
68
+ // 修复信任悖论:两个预设的 commit 都不可自动放行
69
+ (0, vitest_1.expect)(agent_permissions_1.PRESET_PATROL.commit).toBe("deny");
70
+ (0, vitest_1.expect)(agent_permissions_1.PRESET_AGENT.commit).toBe("deny");
71
+ });
72
+ (0, vitest_1.it)("审批未通过时审计事件带 denied 标记", () => {
73
+ const d = (0, agent_permissions_1.decidePermission)("agent", { level: "exec", target: "pytest", projectPath: "/p" });
74
+ (0, vitest_1.expect)(d.audit.detail).toContain("denied");
75
+ });
76
+ });
package/dist/audit.js CHANGED
@@ -66,7 +66,11 @@ function auditDirectory(dir, threshold = DEFAULT_THRESHOLD) {
66
66
  if (!stat.isDirectory()) {
67
67
  return result;
68
68
  }
69
- scanDir(dir, dir, result);
69
+ // Allowlist(.progmune_allowlist):豁免名单中的文件不参与覆盖率分母——
70
+ // 祖父条款:存量手写代码一次入册,新文件仍受覆盖要求约束。
71
+ // 匹配相对 allowlist 所在目录(通常为项目根),而非被扫描目录。
72
+ const allowlist = loadAllowlist(dir);
73
+ scanDir(dir, dir, result, allowlist);
70
74
  result.coverage = result.totalFiles > 0
71
75
  ? result.progmuneFiles / result.totalFiles
72
76
  : 0;
@@ -84,7 +88,46 @@ function auditDirectory(dir, threshold = DEFAULT_THRESHOLD) {
84
88
  }
85
89
  const MARKER_REGEX = /@progmune-generated\s+session=(\S+)(?:\s+timestamp=(\S+))?(?:\s+ruleHash=(\S+))?/;
86
90
  const EXCLUDED_DIRS = new Set(["node_modules", ".git", "dist", ".progmune_corpus", ".progmune_memory"]);
87
- function scanDir(rootDir, currentDir, result) {
91
+ /** 读取 .progmune_allowlist:从被扫描目录向上查找,返回匹配函数(相对 allowlist 所在目录)。 */
92
+ function loadAllowlist(dir) {
93
+ let root = dir;
94
+ let allowlistPath = "";
95
+ for (let i = 0; i < 4; i++) {
96
+ const p = path.join(root, ".progmune_allowlist");
97
+ if (fs.existsSync(p)) {
98
+ allowlistPath = p;
99
+ break;
100
+ }
101
+ const parent = path.dirname(root);
102
+ if (parent === root)
103
+ break;
104
+ root = parent;
105
+ }
106
+ if (!allowlistPath)
107
+ return { root: dir, match: () => false };
108
+ try {
109
+ const patterns = fs.readFileSync(allowlistPath, "utf-8")
110
+ .split("\n")
111
+ .map((l) => l.trim())
112
+ .filter((l) => l.length > 0 && !l.startsWith("#"));
113
+ return {
114
+ root: path.dirname(allowlistPath),
115
+ match: (relPath) => {
116
+ const normalized = relPath.replace(/\\/g, "/");
117
+ return patterns.some((p) => {
118
+ const pat = p.replace(/^\.\//, ""); // 兼容 "./foo.ts" 写法
119
+ if (pat.endsWith("*"))
120
+ return normalized.startsWith(pat.slice(0, -1));
121
+ return normalized === pat || normalized.startsWith(pat.replace(/\/$/, "") + "/");
122
+ });
123
+ },
124
+ };
125
+ }
126
+ catch {
127
+ return { root: dir, match: () => false };
128
+ }
129
+ }
130
+ function scanDir(rootDir, currentDir, result, allowlist) {
88
131
  let entries;
89
132
  try {
90
133
  entries = fs.readdirSync(currentDir, { withFileTypes: true });
@@ -96,7 +139,7 @@ function scanDir(rootDir, currentDir, result) {
96
139
  const fullPath = path.join(currentDir, entry.name);
97
140
  if (entry.isDirectory()) {
98
141
  if (!EXCLUDED_DIRS.has(entry.name) && !entry.name.startsWith(".")) {
99
- scanDir(rootDir, fullPath, result);
142
+ scanDir(rootDir, fullPath, result, allowlist);
100
143
  }
101
144
  continue;
102
145
  }
@@ -104,6 +147,10 @@ function scanDir(rootDir, currentDir, result) {
104
147
  if (!entry.name.endsWith(".ts") && !entry.name.endsWith(".tsx") && !entry.name.endsWith(".mjs")) {
105
148
  continue;
106
149
  }
150
+ // 豁免名单(祖父条款):不在覆盖率分母内——相对 allowlist 根匹配
151
+ const rel = path.relative(allowlist.root, fullPath);
152
+ if (allowlist.match(rel))
153
+ continue;
107
154
  result.totalFiles++;
108
155
  try {
109
156
  const content = fs.readFileSync(fullPath, "utf-8");
package/dist/check.js CHANGED
@@ -117,10 +117,16 @@ if (cliArg === "--ledger") {
117
117
  const rebuilt = (0, ssg_validator_1.rebuildState)(allTransitions, nsInit);
118
118
  const lastTransition = allTransitions[allTransitions.length - 1];
119
119
  const recorded = lastTransition.statesAfter;
120
- const allNs = new Set([...Object.keys(rebuilt), ...Object.keys(recorded)]);
120
+ // checkLedgerConsistency 同规则:只比较 recorded 中有过非空快照的 ns——
121
+ // 早期 session 对 file/db 等记录空数组(无信息),不参与比较。
122
+ const informativeNs = new Set();
123
+ for (const [ns, s] of Object.entries(recorded)) {
124
+ if ((s || []).length > 0)
125
+ informativeNs.add(ns);
126
+ }
121
127
  const norm = (snap) => {
122
128
  const out = {};
123
- for (const ns of [...allNs].sort())
129
+ for (const ns of [...informativeNs].sort())
124
130
  out[ns] = [...(snap[ns] || [])].sort();
125
131
  return out;
126
132
  };
@@ -307,6 +313,35 @@ else {
307
313
  }
308
314
  }
309
315
  // ── 4. Ledger 不变量检查 (Phase 3) ──
316
+ /**
317
+ * 历史约定兼容:早期 session 以 "INIT" 作为 _global 初始状态
318
+ * (当前约定 UNAUTHENTICATED;当前 148 条协议规则已不含 INIT 状态)。
319
+ * 返回规范化视图(仅比较用,不改盘)与受影响转移数。
320
+ */
321
+ function normalizeLegacyInit(transitions, nsInit) {
322
+ let migrated = 0;
323
+ const view = transitions.map((t) => {
324
+ const normSnap = (snap) => {
325
+ const out = {};
326
+ let changed = false;
327
+ for (const [ns, states] of Object.entries(snap)) {
328
+ const currentInit = nsInit.get(ns);
329
+ if (currentInit && currentInit !== "INIT" && states.length === 1 && states[0] === "INIT") {
330
+ out[ns] = [currentInit];
331
+ changed = true;
332
+ }
333
+ else {
334
+ out[ns] = [...states];
335
+ }
336
+ }
337
+ if (changed)
338
+ migrated++;
339
+ return out;
340
+ };
341
+ return { ...t, statesBefore: normSnap(t.statesBefore), statesAfter: normSnap(t.statesAfter) };
342
+ });
343
+ return { view, migrated };
344
+ }
310
345
  step("4/6 Ledger 不变量");
311
346
  {
312
347
  // Load namespace initial states from protocols.json for correct replay
@@ -314,6 +349,7 @@ step("4/6 Ledger 不变量");
314
349
  let checked = 0;
315
350
  let consistent = 0;
316
351
  let stateMatch = 0;
352
+ let legacyInitMigrations = 0;
317
353
  const allLedgers = [];
318
354
  const violationsDetail = [];
319
355
  const replayMismatchDetail = [];
@@ -335,9 +371,15 @@ step("4/6 Ledger 不变量");
335
371
  const transitions = attempt.transitions || [];
336
372
  if (transitions.length === 0)
337
373
  continue;
338
- allLedgers.push(...transitions);
374
+ // 历史约定兼容:早期 session 以 "INIT" 作为 _global 初始状态
375
+ // (当前约定 UNAUTHENTICATED;当前协议规则已不含 INIT)。
376
+ // 规范化视图只用于比较,不改盘。
377
+ const { view, migrated } = normalizeLegacyInit(transitions, nsInit);
378
+ if (migrated > 0)
379
+ legacyInitMigrations++;
380
+ allLedgers.push(...view);
339
381
  // Invariant check
340
- const result = (0, ssg_validator_1.checkLedgerConsistency)(transitions, nsInit);
382
+ const result = (0, ssg_validator_1.checkLedgerConsistency)(view, nsInit);
341
383
  checked++;
342
384
  if (result.consistent) {
343
385
  consistent++;
@@ -348,10 +390,16 @@ step("4/6 Ledger 不变量");
348
390
  }
349
391
  }
350
392
  // Replay check: rebuildState === recorded statesAfter
351
- const rebuilt = (0, ssg_validator_1.rebuildState)(transitions, nsInit);
352
- const recorded = transitions[transitions.length - 1].statesAfter;
353
- const allNs = new Set([...Object.keys(rebuilt), ...Object.keys(recorded)]);
354
- if (JSON.stringify(norm(rebuilt, allNs)) === JSON.stringify(norm(recorded, allNs))) {
393
+ // 只比较 recorded 中有过非空快照的 ns(早期 session 对部分 ns
394
+ // 记录空数组,不携带可比较的状态信息)
395
+ const rebuilt = (0, ssg_validator_1.rebuildState)(view, nsInit);
396
+ const recorded = view[view.length - 1].statesAfter;
397
+ const informativeNs = new Set();
398
+ for (const [ns, s] of Object.entries(recorded)) {
399
+ if ((s || []).length > 0)
400
+ informativeNs.add(ns);
401
+ }
402
+ if (JSON.stringify(norm(rebuilt, informativeNs)) === JSON.stringify(norm(recorded, informativeNs))) {
355
403
  stateMatch++;
356
404
  }
357
405
  else {
@@ -368,6 +416,9 @@ step("4/6 Ledger 不变量");
368
416
  else if (consistent === checked && stateMatch === checked) {
369
417
  const combinedHash = (0, ssg_validator_1.hashLedger)(allLedgers);
370
418
  pass(`全部 ${checked} 个 Ledger 通过 (Invariant-0 + Invariant-1 + Replay) | 完整性指纹: ${combinedHash}`);
419
+ if (legacyInitMigrations > 0) {
420
+ warn(`历史约定兼容:${legacyInitMigrations} 条转移的初始状态 INIT 已按当前约定(${nsInit.get("_global")})规范化比较(不改盘)`);
421
+ }
371
422
  }
372
423
  else {
373
424
  if (consistent < checked) {
@@ -404,7 +455,9 @@ step("4/6 Ledger 不变量");
404
455
  if (transitions.length === 0)
405
456
  continue;
406
457
  try {
407
- (0, runtime_invariants_1.assertLedgerInvariants)(transitions, nsInit);
458
+ // 历史约定兼容:与主检查一致,先规范化旧 INIT 初值
459
+ const { view } = normalizeLegacyInit(transitions, nsInit);
460
+ (0, runtime_invariants_1.assertLedgerInvariants)(view, nsInit);
408
461
  }
409
462
  catch (e) {
410
463
  if (e instanceof runtime_invariants_1.InvariantViolationError) {
@@ -52,6 +52,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
52
52
  const path = __importStar(require("path"));
53
53
  const agent_patrol_1 = require("./agent-patrol");
54
54
  const agent_perception_1 = require("./agent-perception");
55
+ const agent_permissions_1 = require("./agent-permissions");
55
56
  // 在 chdir 到项目目录之前按启动 CWD 加载 .env——
56
57
  // trust 引擎内部的 lazy require(语义映射 LLM 回退)发生在 chdir 之后,
57
58
  // 若不预载,LLM_API_KEY 不可用,映射降级会导致漏报。
@@ -90,13 +91,24 @@ const json = args.includes("--json");
90
91
  async function scanOnce(label) {
91
92
  try {
92
93
  const report = await (0, agent_patrol_1.runPatrol)(projectPath);
93
- const reportFile = (0, agent_patrol_1.writePatrolReport)(report, projectPath);
94
+ // ── P5 安全层:报告写入经 FsSandbox(巡逻预设:写=沙箱白名单) ──
95
+ const writeDecision = (0, agent_permissions_1.decidePermission)("patrol", {
96
+ level: "write",
97
+ target: path.join(projectPath, ".progmune_patrol_report.md"),
98
+ projectPath,
99
+ });
100
+ let reportFile = "";
101
+ if (writeDecision.allowed) {
102
+ reportFile = (0, agent_patrol_1.writePatrolReport)(report, projectPath);
103
+ }
94
104
  if (json && !watch) {
95
105
  console.log(JSON.stringify(report, null, 2));
96
106
  }
97
107
  else {
98
108
  console.log(`[${label}] ` + (0, agent_patrol_1.formatPatrolTerminal)(report).replace(/\n/g, "\n "));
99
- console.log(` 报告: ${reportFile}`);
109
+ console.log(writeDecision.allowed
110
+ ? ` 报告: ${reportFile}`
111
+ : ` ⚠️ 报告写入被沙箱拒绝: ${writeDecision.detail}`);
100
112
  }
101
113
  }
102
114
  catch (e) {
@@ -68,9 +68,22 @@ function getProtocolConfig() {
68
68
  let rules = [];
69
69
  let version = "1.0";
70
70
  const protoPath = path.resolve(process.env.PROGMUNE_PROJECT_DIR || process.cwd(), "protocols.json");
71
- if (fs.existsSync(protoPath)) {
71
+ // 解析顺序与 loadIR 一致:显式目录 → CWD → 包目录回退。
72
+ // 修复:在无 protocols.json 的项目目录里运行时(如 agent CLI chdir 到
73
+ // demo-project),此前 nsInit 退化为仅 _global —— session 只记录 1 个
74
+ // 命名空间,而 check 在仓库根跑用全量 27 个 ns 重建 → before-consistency
75
+ // 全量误报(1308/1308)。包目录回退保证任何 cwd 下世界一致。
76
+ const candidates = [protoPath];
77
+ try {
78
+ candidates.push(path.resolve(__dirname, "../protocols.json"));
79
+ }
80
+ catch { /* __dirname 不可用时跳过 */ }
81
+ let loaded = false;
82
+ for (const p of candidates) {
83
+ if (!fs.existsSync(p))
84
+ continue;
72
85
  try {
73
- const proto = JSON.parse(fs.readFileSync(protoPath, "utf-8"));
86
+ const proto = JSON.parse(fs.readFileSync(p, "utf-8"));
74
87
  version = proto.$schema || proto.version || "1.0";
75
88
  // Load namespace initial states
76
89
  nsInit.set("_global", "UNAUTHENTICATED");
@@ -81,11 +94,13 @@ function getProtocolConfig() {
81
94
  }
82
95
  // Parse rules
83
96
  rules = (0, ssg_validator_1.parseProtocolsFromJSON)(proto);
97
+ loaded = true;
98
+ break;
84
99
  }
85
- catch { /* protocol load — optional */ }
100
+ catch { /* 下一个候选 */ }
86
101
  }
87
- else {
88
- // Fallback: minimal defaults (no protocols.json found)
102
+ if (!loaded) {
103
+ // Fallback: minimal defaults (no protocols.json anywhere)
89
104
  nsInit.set("_global", "UNAUTHENTICATED");
90
105
  }
91
106
  // Compute rule hash
@@ -308,10 +308,26 @@ function checkLedgerConsistency(ledger, namespaceInitialStates = new Map([["_glo
308
308
  running.set(ns, new Set());
309
309
  }
310
310
  }
311
- // Normalize a snapshot: ensure all known namespaces are present
311
+ // Normalize a snapshot: 只比较 ledger 中实际出现过的命名空间。
312
+ // 历史 session 只记录其触及的命名空间(protocol-registry 包目录回退修复前,
313
+ // 无 protocols.json 的 cwd 下 nsInit 退化为仅 _global)——用全量 nsInit
314
+ // 重建时未记录的 ns 不应参与比较,否则旧数据 before-consistency 全量误报。
315
+ // 更严格一步:只记录"有过非空快照"的 ns——早期 session 对 file/db 等
316
+ // 记录空数组(键存在但无信息),空数组不携带可比较的状态信息。
317
+ const recordedNamespaces = new Set();
318
+ for (const t of ledger) {
319
+ for (const [ns, states] of Object.entries(t.statesBefore)) {
320
+ if ((states || []).length > 0)
321
+ recordedNamespaces.add(ns);
322
+ }
323
+ for (const [ns, states] of Object.entries(t.statesAfter)) {
324
+ if ((states || []).length > 0)
325
+ recordedNamespaces.add(ns);
326
+ }
327
+ }
312
328
  function normalizeSnap(snap) {
313
329
  const out = {};
314
- for (const ns of allNamespaces) {
330
+ for (const ns of recordedNamespaces) {
315
331
  out[ns] = [...(snap[ns] || [])].sort();
316
332
  }
317
333
  return out;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "progmune-runtime",
3
- "version": "3.4.0",
3
+ "version": "3.4.1",
4
4
  "description": "Progmune — AI Trust Decision Engine. Verify AI-generated code before it reaches production. Outputs APPROVED / NEEDS_REVIEW / BLOCKED with evidence.",
5
5
  "files": [
6
6
  "dist/",