Files
my-pi/pi-permission-system/test/helpers/manager-harness.ts
T
云服务部-叶林立andDevin <158243242+devin-ai-integration[bot]@users.noreply.github.com> 2682bd7fa7 feat: 组合包配置集中到 my-pi/ 目录并改为整体重建
- 组合包拥有、可随时重建的配置、日志与缓存统一放在
  <agentDir>/my-pi/:permission-system/(policy.jsonc、hard-guards.jsonc、
  logs/)、rtk-optimizer/config.json、tool-search/(config.json、
  catalog-v1.json)与 system-prompt-cover.md。hashline.json、lsp.json
  由外部扩展读取固定路径,是唯一例外。
- 新增 config/bundle-manifest.json 与 scripts/rebuild-bundle-config.mjs:
  先校验全部来源与目标,在临时目录构建完整树,再整体删除旧 my-pi/
  (符号链接只删链接)并原子替换,不备份。install.sh / update.sh 每次
  运行都调用它;扩展自身不再播种或迁移配置。
- update.sh 删除 pi update 失败后的 git clean 恢复逻辑:Pi 1.3.0 会在
  下一次 pi update 时依据中断标记自行恢复。同时删除 Tool Search
  settings.json 快照迁移与封面部署脚本。
- Tool Search 改为读取 my-pi/tool-search/config.json(源为
  config/tool-search.json,须与 BUNDLE_TOOL_SEARCH_DEFAULTS 一致),
  不再读写 settings.json 的 toolSearch 段,移除 bundleDefaultsVersion。
- 默认权限策略开启 debugLog。
- 旧位置的残留文件不迁移、不清理;AGENTS.md / README 同步新约束。

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-19 02:26:57 -07:00

268 lines
7.8 KiB
TypeScript

/**
* Filesystem-backed PermissionManager harness for integration tests.
*
* Writes a real config file and agents directory to a temp directory so
* PermissionManager can load them without mocking the file system.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { getGlobalConfigPath } from "#src/config-paths";
import { PermissionManager, type PolicyLoader } from "#src/permission-manager";
import type { ResolvedPolicyPaths } from "#src/policy-loader";
import type { Rule } from "#src/rule";
import type { PermissionState, ScopeConfig } from "#src/types";
/**
* Minimal in-memory PolicyLoader for testing merge + evaluation logic
* without touching the filesystem.
*/
export function createInMemoryPolicyLoader(
scopes: {
global?: ScopeConfig;
agent?: Record<string, ScopeConfig>;
projectAgent?: Record<string, ScopeConfig>;
} = {},
mcpServerNames: readonly string[] = [],
): PolicyLoader {
const issues: string[] = [];
return {
loadGlobalConfig: () => scopes.global ?? ({} as const),
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- || is intentional: handles both falsy name and missing key
loadAgentConfig: (name?: string) => (name && scopes.agent?.[name]) || {},
loadProjectAgentConfig: (name?: string) =>
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- || is intentional: handles both falsy name and missing key
(name && scopes.projectAgent?.[name]) || {},
getConfiguredMcpServerNames: () => mcpServerNames,
getCacheStamp: () => "in-memory",
getConfigIssues: () => issues,
getResolvedPolicyPaths: (): ResolvedPolicyPaths => ({
globalConfigPath: "/in-memory/config.json",
globalConfigExists: true,
agentsDir: "/in-memory/agents",
agentsDirExists: false,
projectAgentsDir: null,
projectAgentsDirExists: false,
}),
};
}
/** Manager backed by an in-memory PolicyLoader — no filesystem required. */
export function createInMemoryManager(
scopes: Parameters<typeof createInMemoryPolicyLoader>[0] = {},
mcpServerNames: readonly string[] = [],
): PermissionManager {
return new PermissionManager({
policyLoader: createInMemoryPolicyLoader(scopes, mcpServerNames),
});
}
/** Manager backed by nonexistent config paths — universal default is "ask". */
export function createMissingConfigManager(
mcpServerNames: readonly string[] = [],
): PermissionManager {
return new PermissionManager({
globalConfigPath: "/nonexistent/config.json",
agentsDir: "/nonexistent/agents",
mcpServerNames: [...mcpServerNames],
});
}
/** Build a session-layer rule (default action "allow"). */
export function sessionRule(
surface: string,
pattern: string,
action: PermissionState = "allow",
): Rule {
return { surface, pattern, action, layer: "session", origin: "session" };
}
export type CreateManagerOptions = {
mcpServerNames?: readonly string[];
};
export type CreateManagerWithProjectOptions = CreateManagerOptions & {
projectConfig?: ScopeConfig;
projectAgentFiles?: Record<string, string>;
};
export function createManager(
config: ScopeConfig,
agentFiles: Record<string, string> = {},
options: CreateManagerOptions = {},
) {
const baseDir = mkdtempSync(join(tmpdir(), "pi-permission-system-test-"));
const globalConfigPath = join(baseDir, "pi-permissions.jsonc");
const agentsDir = join(baseDir, "agents");
mkdirSync(agentsDir, { recursive: true });
writeFileSync(
globalConfigPath,
`${JSON.stringify(config, null, 2)}\n`,
"utf8",
);
for (const [name, content] of Object.entries(agentFiles)) {
writeFileSync(join(agentsDir, `${name}.md`), content, "utf8");
}
const manager = new PermissionManager({
globalConfigPath,
agentsDir,
mcpServerNames: options.mcpServerNames,
});
return {
manager,
globalConfigPath,
cleanup: (): void => {
rmSync(baseDir, { recursive: true, force: true });
},
};
}
/**
* Manager backed by a temp config holding only a permission map.
* Delegates to createManager; returns the manager and its cleanup.
*/
export function createManagerWithConfig(
permission: Record<string, unknown>,
mcpServerNames: readonly string[] = [],
): { manager: PermissionManager; cleanup: () => void } {
const { manager, cleanup } = createManager(
{ permission } as ScopeConfig,
{},
{ mcpServerNames },
);
return { manager, cleanup };
}
export function createManagerWithProject(
config: ScopeConfig,
agentFiles: Record<string, string> = {},
options: CreateManagerWithProjectOptions = {},
) {
const baseDir = mkdtempSync(
join(tmpdir(), "pi-permission-system-proj-test-"),
);
const globalConfigPath = join(baseDir, "pi-permissions.jsonc");
const agentsDir = join(baseDir, "agents");
const projectRoot = join(baseDir, "project");
const projectGlobalConfigPath = join(projectRoot, "pi-permissions.jsonc");
const projectAgentsDir = join(projectRoot, "agents");
mkdirSync(agentsDir, { recursive: true });
mkdirSync(projectAgentsDir, { recursive: true });
writeFileSync(
globalConfigPath,
`${JSON.stringify(config, null, 2)}\n`,
"utf8",
);
if (options.projectConfig) {
writeFileSync(
projectGlobalConfigPath,
`${JSON.stringify(options.projectConfig, null, 2)}\n`,
"utf8",
);
}
for (const [name, content] of Object.entries(agentFiles)) {
writeFileSync(join(agentsDir, `${name}.md`), content, "utf8");
}
for (const [name, content] of Object.entries(
options.projectAgentFiles ?? {},
)) {
writeFileSync(join(projectAgentsDir, `${name}.md`), content, "utf8");
}
const manager = new PermissionManager({
globalConfigPath,
agentsDir,
projectAgentsDir,
mcpServerNames: options.mcpServerNames,
});
return {
manager,
cleanup: (): void => {
rmSync(baseDir, { recursive: true, force: true });
},
};
}
/**
* Manager backed by a global permission map plus an optional project map.
* Delegates to createManagerWithProject; returns the manager and its cleanup.
*/
export function createManagerWithScopes(
globalPermission: Record<string, unknown>,
projectPermission?: Record<string, unknown>,
): { manager: PermissionManager; cleanup: () => void } {
return createManagerWithProject(
{ permission: globalPermission } as ScopeConfig,
{},
{
projectConfig:
projectPermission === undefined
? undefined
: ({ permission: projectPermission } as ScopeConfig),
},
);
}
/**
* Build a temp agentDir with a global config and an optional cwd with a
* project config. Returns the paths and a cleanup function.
*/
export function createAgentDirHarness(opts: {
globalPermission: Record<string, unknown>;
projectPermission?: Record<string, unknown>;
}): {
agentDir: string;
cwd: string;
globalConfigPath: string;
projectConfigPath: string;
cleanup: () => void;
} {
const baseDir = mkdtempSync(join(tmpdir(), "pm-agent-dir-test-"));
const agentDir = join(baseDir, "agent");
const cwd = join(baseDir, "project");
const globalConfigPath = getGlobalConfigPath(agentDir);
mkdirSync(dirname(globalConfigPath), {
recursive: true,
});
writeFileSync(
globalConfigPath,
JSON.stringify({ permission: opts.globalPermission }, null, 2),
);
const projectConfigPath = join(
cwd,
".pi",
"extensions",
"pi-permission-system",
"policy.jsonc",
);
mkdirSync(join(cwd, ".pi", "extensions", "pi-permission-system"), {
recursive: true,
});
if (opts.projectPermission) {
writeFileSync(
projectConfigPath,
JSON.stringify({ permission: opts.projectPermission }, null, 2),
);
}
return {
agentDir,
cwd,
globalConfigPath,
projectConfigPath,
cleanup: () => rmSync(baseDir, { recursive: true, force: true }),
};
}