@gotgenes/pi-permission-system 18.1.0 → 18.1.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.
Files changed (132) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/docs/assets/logo.png +0 -0
  3. package/docs/assets/logo.svg +213 -0
  4. package/docs/configuration.md +700 -0
  5. package/docs/cross-extension-api.md +525 -0
  6. package/docs/guides/permission-frontmatter-for-subagent-extensions.md +201 -0
  7. package/docs/guides/upstream-issue-template.md +113 -0
  8. package/docs/migration/legacy-to-flat.md +365 -0
  9. package/docs/opencode-compatibility.md +213 -0
  10. package/docs/session-approvals.md +68 -0
  11. package/docs/subagent-integration.md +102 -0
  12. package/docs/troubleshooting.md +53 -0
  13. package/package.json +5 -2
  14. package/src/access-intent/access-path.ts +29 -4
  15. package/src/access-intent/bash/bash-path-resolver.ts +39 -18
  16. package/src/access-intent/bash/msys-bash-tokens.ts +64 -0
  17. package/src/path-normalizer.ts +105 -2
  18. package/test/access-intent/access-path.test.ts +0 -277
  19. package/test/access-intent/bash/node-text.test.ts +0 -148
  20. package/test/access-intent/bash/parser.test.ts +0 -19
  21. package/test/access-intent/bash/program.test.ts +0 -673
  22. package/test/access-intent/bash/token-classification.test.ts +0 -363
  23. package/test/access-intent/bash/token-collection.test.ts +0 -300
  24. package/test/active-agent.test.ts +0 -155
  25. package/test/async-cache.test.ts +0 -48
  26. package/test/bash-arity.test.ts +0 -144
  27. package/test/bash-external-directory.test.ts +0 -1022
  28. package/test/builtin-tool-input-formatters.test.ts +0 -109
  29. package/test/canonicalize-path.test.ts +0 -119
  30. package/test/composition-root.test.ts +0 -698
  31. package/test/config-loader.test.ts +0 -740
  32. package/test/config-modal.test.ts +0 -320
  33. package/test/config-paths.test.ts +0 -83
  34. package/test/config-pipeline.test.ts +0 -90
  35. package/test/config-reporter.test.ts +0 -147
  36. package/test/config-store.test.ts +0 -466
  37. package/test/decision-audit.test.ts +0 -72
  38. package/test/decision-reporter.test.ts +0 -112
  39. package/test/denial-messages.test.ts +0 -714
  40. package/test/detect-permissive-bash-fallback.test.ts +0 -56
  41. package/test/expand-home.test.ts +0 -93
  42. package/test/extension-config.test.ts +0 -129
  43. package/test/extension-paths.test.ts +0 -108
  44. package/test/forwarded-permissions/io.test.ts +0 -251
  45. package/test/forwarding-manager.test.ts +0 -200
  46. package/test/handlers/before-agent-start.test.ts +0 -314
  47. package/test/handlers/external-directory-integration.test.ts +0 -515
  48. package/test/handlers/external-directory-session-dedup.test.ts +0 -175
  49. package/test/handlers/external-directory-symlink-acceptance.test.ts +0 -167
  50. package/test/handlers/gates/bash-command-metamorphic.test.ts +0 -88
  51. package/test/handlers/gates/bash-command.test.ts +0 -257
  52. package/test/handlers/gates/bash-external-directory.test.ts +0 -268
  53. package/test/handlers/gates/bash-path.test.ts +0 -346
  54. package/test/handlers/gates/candidate-check.test.ts +0 -52
  55. package/test/handlers/gates/external-directory-messages.test.ts +0 -85
  56. package/test/handlers/gates/external-directory-policy.test.ts +0 -134
  57. package/test/handlers/gates/external-directory.test.ts +0 -267
  58. package/test/handlers/gates/helpers.test.ts +0 -165
  59. package/test/handlers/gates/path.test.ts +0 -369
  60. package/test/handlers/gates/runner.test.ts +0 -408
  61. package/test/handlers/gates/skill-input-gate-pipeline.test.ts +0 -176
  62. package/test/handlers/gates/skill-input.test.ts +0 -128
  63. package/test/handlers/gates/skill-read.test.ts +0 -161
  64. package/test/handlers/gates/tool-call-gate-pipeline.test.ts +0 -356
  65. package/test/handlers/gates/tool.test.ts +0 -244
  66. package/test/handlers/input-events.test.ts +0 -168
  67. package/test/handlers/input.test.ts +0 -199
  68. package/test/handlers/lifecycle.test.ts +0 -221
  69. package/test/handlers/tool-call-boundary.test.ts +0 -145
  70. package/test/handlers/tool-call-events.test.ts +0 -277
  71. package/test/handlers/tool-call.test.ts +0 -395
  72. package/test/handlers/validate-requested-tool.test.ts +0 -92
  73. package/test/helpers/external-directory-fixtures.ts +0 -269
  74. package/test/helpers/gate-fixtures.ts +0 -316
  75. package/test/helpers/handler-fixtures.ts +0 -335
  76. package/test/helpers/make-fake-pi.ts +0 -100
  77. package/test/helpers/manager-harness.ts +0 -112
  78. package/test/helpers/session-fixtures.ts +0 -199
  79. package/test/input-normalizer.test.ts +0 -325
  80. package/test/logging.test.ts +0 -51
  81. package/test/mcp-targets.test.ts +0 -233
  82. package/test/node-modules-discovery.test.ts +0 -97
  83. package/test/normalize.test.ts +0 -247
  84. package/test/path-containment.test.ts +0 -161
  85. package/test/path-normalization.test.ts +0 -233
  86. package/test/path-normalizer.test.ts +0 -196
  87. package/test/path-surfaces.test.ts +0 -55
  88. package/test/pattern-suggest.test.ts +0 -248
  89. package/test/permission-dialog.test.ts +0 -205
  90. package/test/permission-event-rpc.test.ts +0 -560
  91. package/test/permission-events.test.ts +0 -400
  92. package/test/permission-forwarder.test.ts +0 -370
  93. package/test/permission-forwarding.test.ts +0 -315
  94. package/test/permission-gate.test.ts +0 -269
  95. package/test/permission-manager-unified.test.ts +0 -3714
  96. package/test/permission-merge.test.ts +0 -61
  97. package/test/permission-prompter.test.ts +0 -518
  98. package/test/permission-prompts.test.ts +0 -363
  99. package/test/permission-resolver.test.ts +0 -277
  100. package/test/permission-session.test.ts +0 -404
  101. package/test/permission-ui-prompt.test.ts +0 -146
  102. package/test/permissions-service.test.ts +0 -192
  103. package/test/pi-infrastructure-read.test.ts +0 -432
  104. package/test/policy-loader.test.ts +0 -561
  105. package/test/prompting-gateway.test.ts +0 -231
  106. package/test/rule.test.ts +0 -650
  107. package/test/safe-system-paths.test.ts +0 -46
  108. package/test/scope-merge.test.ts +0 -116
  109. package/test/service-lifecycle.test.ts +0 -163
  110. package/test/service.test.ts +0 -261
  111. package/test/session-approval.test.ts +0 -75
  112. package/test/session-logger.test.ts +0 -200
  113. package/test/session-rules.test.ts +0 -321
  114. package/test/session-start.test.ts +0 -112
  115. package/test/skill-prompt-sanitizer.test.ts +0 -418
  116. package/test/status.test.ts +0 -10
  117. package/test/subagent-context.test.ts +0 -372
  118. package/test/subagent-lifecycle-events.test.ts +0 -132
  119. package/test/subagent-registry.test.ts +0 -145
  120. package/test/synthesize.test.ts +0 -302
  121. package/test/system-prompt-sanitizer.test.ts +0 -382
  122. package/test/tool-access-extractor-registry.test.ts +0 -77
  123. package/test/tool-input-formatter-registry.test.ts +0 -75
  124. package/test/tool-input-path.test.ts +0 -84
  125. package/test/tool-input-preview.test.ts +0 -129
  126. package/test/tool-input-prompt-formatters.test.ts +0 -115
  127. package/test/tool-preview-formatter.test.ts +0 -458
  128. package/test/tool-registry.test.ts +0 -197
  129. package/test/value-guards.test.ts +0 -193
  130. package/test/wildcard-matcher.test.ts +0 -424
  131. package/test/yaml-frontmatter.test.ts +0 -91
  132. package/test/yolo-mode.test.ts +0 -188
@@ -1,56 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
-
3
- import { detectPermissiveBashFallback } from "#src/config-loader";
4
- import type { FlatPermissionConfig } from "#src/types";
5
-
6
- describe("detectPermissiveBashFallback", () => {
7
- it("warns when top-level '*' is allow and bash is absent", () => {
8
- const permission: FlatPermissionConfig = { "*": "allow" };
9
-
10
- const issue = detectPermissiveBashFallback(permission);
11
-
12
- expect(issue).toBeDefined();
13
- expect(issue).toContain("bash");
14
- expect(issue).toContain("allow");
15
- });
16
-
17
- it("warns when top-level '*' is allow and bash map has no '*' key", () => {
18
- const permission: FlatPermissionConfig = {
19
- "*": "allow",
20
- bash: { "git *": "ask" },
21
- };
22
-
23
- expect(detectPermissiveBashFallback(permission)).toBeDefined();
24
- });
25
-
26
- it("does not warn when bash is a bare string surface", () => {
27
- const permission: FlatPermissionConfig = { "*": "allow", bash: "ask" };
28
-
29
- expect(detectPermissiveBashFallback(permission)).toBeUndefined();
30
- });
31
-
32
- it("does not warn when bash map has an explicit '*' key", () => {
33
- const permission: FlatPermissionConfig = {
34
- "*": "allow",
35
- bash: { "*": "ask", "git *": "allow" },
36
- };
37
-
38
- expect(detectPermissiveBashFallback(permission)).toBeUndefined();
39
- });
40
-
41
- it("does not warn when top-level '*' is not allow", () => {
42
- const permission: FlatPermissionConfig = { "*": "ask" };
43
-
44
- expect(detectPermissiveBashFallback(permission)).toBeUndefined();
45
- });
46
-
47
- it("does not warn when top-level '*' is absent", () => {
48
- const permission: FlatPermissionConfig = { bash: { "git *": "ask" } };
49
-
50
- expect(detectPermissiveBashFallback(permission)).toBeUndefined();
51
- });
52
-
53
- it("does not warn when permission is undefined", () => {
54
- expect(detectPermissiveBashFallback(undefined)).toBeUndefined();
55
- });
56
- });
@@ -1,93 +0,0 @@
1
- import { join } from "node:path";
2
- import { afterEach, describe, expect, test, vi } from "vitest";
3
-
4
- const mockHomedir = vi.hoisted(() => vi.fn(() => "/home/testuser"));
5
-
6
- vi.mock("node:os", () => ({
7
- homedir: mockHomedir,
8
- default: { homedir: mockHomedir },
9
- }));
10
-
11
- import { expandHomePath } from "#src/expand-home";
12
-
13
- const FAKE_HOME = "/home/testuser";
14
-
15
- afterEach(() => {
16
- mockHomedir.mockClear();
17
- });
18
-
19
- describe("expandHomePath", () => {
20
- describe("~ expansion", () => {
21
- test("bare ~ expands to homedir()", () => {
22
- expect(expandHomePath("~")).toBe(FAKE_HOME);
23
- });
24
-
25
- test("~/path expands to homedir()/path", () => {
26
- expect(expandHomePath("~/dev/project")).toBe(
27
- join(FAKE_HOME, "dev/project"),
28
- );
29
- });
30
-
31
- test("~/path/* expands to homedir()/path/*", () => {
32
- expect(expandHomePath("~/dev/*")).toBe(join(FAKE_HOME, "dev/*"));
33
- });
34
-
35
- test("~\\ (Windows separator) expands to homedir() + rest", () => {
36
- expect(expandHomePath("~\\dev\\project")).toBe(
37
- join(FAKE_HOME, "dev\\project"),
38
- );
39
- });
40
-
41
- test("~username (no separator) is not expanded (no-op)", () => {
42
- expect(expandHomePath("~username")).toBe("~username");
43
- });
44
- });
45
-
46
- describe("$HOME expansion", () => {
47
- test("bare $HOME expands to homedir()", () => {
48
- expect(expandHomePath("$HOME")).toBe(FAKE_HOME);
49
- });
50
-
51
- test("$HOME/path expands to homedir()/path", () => {
52
- expect(expandHomePath("$HOME/dev/project")).toBe(
53
- join(FAKE_HOME, "dev/project"),
54
- );
55
- });
56
-
57
- test("$HOME/path/* expands to homedir()/path/*", () => {
58
- expect(expandHomePath("$HOME/dev/*")).toBe(join(FAKE_HOME, "dev/*"));
59
- });
60
-
61
- test("$HOME\\ (Windows separator) expands to homedir() + rest", () => {
62
- expect(expandHomePath("$HOME\\dev\\project")).toBe(
63
- join(FAKE_HOME, "dev\\project"),
64
- );
65
- });
66
-
67
- test("$HOMEDIR (no separator) is not expanded (no-op)", () => {
68
- expect(expandHomePath("$HOMEDIR")).toBe("$HOMEDIR");
69
- });
70
- });
71
-
72
- describe("no-op patterns", () => {
73
- test("absolute path is unchanged", () => {
74
- expect(expandHomePath("/usr/local/bin")).toBe("/usr/local/bin");
75
- });
76
-
77
- test("relative path is unchanged", () => {
78
- expect(expandHomePath("dev/project")).toBe("dev/project");
79
- });
80
-
81
- test("glob-only pattern is unchanged", () => {
82
- expect(expandHomePath("*")).toBe("*");
83
- });
84
-
85
- test("empty string is unchanged", () => {
86
- expect(expandHomePath("")).toBe("");
87
- });
88
-
89
- test("bash command pattern starting with a word is unchanged", () => {
90
- expect(expandHomePath("git push *")).toBe("git push *");
91
- });
92
- });
93
- });
@@ -1,129 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
-
3
- import {
4
- detectMisplacedPermissionKeys,
5
- normalizePermissionSystemConfig,
6
- } from "#src/extension-config";
7
-
8
- describe("detectMisplacedPermissionKeys", () => {
9
- it("returns an empty array for a record with only valid extension keys", () => {
10
- const result = detectMisplacedPermissionKeys({
11
- debugLog: true,
12
- permissionReviewLog: true,
13
- yoloMode: false,
14
- });
15
- expect(result).toEqual([]);
16
- });
17
-
18
- it("returns an empty array for an empty record", () => {
19
- const result = detectMisplacedPermissionKeys({});
20
- expect(result).toEqual([]);
21
- });
22
-
23
- it("returns misplaced key names when legacy permission-rule keys are present", () => {
24
- const result = detectMisplacedPermissionKeys({
25
- debugLog: true,
26
- defaultPolicy: { tools: "ask" },
27
- bash: { "git status": "allow" },
28
- });
29
- expect(result).toEqual(["defaultPolicy", "bash"]);
30
- });
31
-
32
- it("detects all known legacy permission-rule keys", () => {
33
- const result = detectMisplacedPermissionKeys({
34
- defaultPolicy: {},
35
- tools: {},
36
- bash: {},
37
- mcp: {},
38
- skills: {},
39
- special: {},
40
- external_directory: {},
41
- });
42
- expect(result).toEqual([
43
- "defaultPolicy",
44
- "tools",
45
- "bash",
46
- "mcp",
47
- "skills",
48
- "special",
49
- "external_directory",
50
- ]);
51
- });
52
-
53
- it("does not detect doom_loop as a misplaced permission key", () => {
54
- const result = detectMisplacedPermissionKeys({
55
- doom_loop: {},
56
- });
57
- expect(result).toEqual([]);
58
- });
59
-
60
- it("does not flag the new flat-format permission key as misplaced", () => {
61
- const result = detectMisplacedPermissionKeys({
62
- debugLog: false,
63
- permission: { "*": "ask" },
64
- });
65
- expect(result).toEqual([]);
66
- });
67
-
68
- it("ignores unknown keys that are not permission-rule keys", () => {
69
- const result = detectMisplacedPermissionKeys({
70
- debugLog: true,
71
- someRandomKey: "value",
72
- });
73
- expect(result).toEqual([]);
74
- });
75
- });
76
-
77
- describe("normalizePermissionSystemConfig", () => {
78
- it("normalizes a valid config object", () => {
79
- const result = normalizePermissionSystemConfig({
80
- debugLog: true,
81
- permissionReviewLog: false,
82
- yoloMode: true,
83
- });
84
- expect(result).toEqual({
85
- debugLog: true,
86
- permissionReviewLog: false,
87
- yoloMode: true,
88
- });
89
- });
90
-
91
- it("defaults debugLog to false when missing", () => {
92
- const result = normalizePermissionSystemConfig({});
93
- expect(result.debugLog).toBe(false);
94
- });
95
-
96
- it("defaults permissionReviewLog to true when missing", () => {
97
- const result = normalizePermissionSystemConfig({});
98
- expect(result.permissionReviewLog).toBe(true);
99
- });
100
-
101
- it("defaults yoloMode to false when missing", () => {
102
- const result = normalizePermissionSystemConfig({});
103
- expect(result.yoloMode).toBe(false);
104
- });
105
-
106
- it("includes toolInputPreviewMaxLength when a valid positive integer is provided", () => {
107
- const result = normalizePermissionSystemConfig({
108
- toolInputPreviewMaxLength: 400,
109
- });
110
- expect(result.toolInputPreviewMaxLength).toBe(400);
111
- });
112
-
113
- it("omits toolInputPreviewMaxLength when absent", () => {
114
- const result = normalizePermissionSystemConfig({});
115
- expect("toolInputPreviewMaxLength" in result).toBe(false);
116
- });
117
-
118
- it("includes toolTextSummaryMaxLength when a valid positive integer is provided", () => {
119
- const result = normalizePermissionSystemConfig({
120
- toolTextSummaryMaxLength: 120,
121
- });
122
- expect(result.toolTextSummaryMaxLength).toBe(120);
123
- });
124
-
125
- it("omits toolTextSummaryMaxLength when absent", () => {
126
- const result = normalizePermissionSystemConfig({});
127
- expect("toolTextSummaryMaxLength" in result).toBe(false);
128
- });
129
- });
@@ -1,108 +0,0 @@
1
- import { join } from "node:path";
2
- import { beforeEach, describe, expect, it, vi } from "vitest";
3
-
4
- const { mockDiscoverGlobalNodeModulesRoot } = vi.hoisted(() => ({
5
- mockDiscoverGlobalNodeModulesRoot: vi.fn<() => string | null>(),
6
- }));
7
-
8
- vi.mock("../src/node-modules-discovery", () => ({
9
- discoverGlobalNodeModulesRoot: mockDiscoverGlobalNodeModulesRoot,
10
- }));
11
-
12
- import { getGlobalLogsDir } from "#src/config-paths";
13
- import { computeExtensionPaths } from "#src/extension-paths";
14
-
15
- describe("computeExtensionPaths", () => {
16
- beforeEach(() => {
17
- mockDiscoverGlobalNodeModulesRoot.mockReset();
18
- mockDiscoverGlobalNodeModulesRoot.mockReturnValue(
19
- "/mock/global/node_modules",
20
- );
21
- });
22
-
23
- it("sets agentDir from argument", () => {
24
- const paths = computeExtensionPaths("/test/agent");
25
- expect(paths.agentDir).toBe("/test/agent");
26
- });
27
-
28
- it("derives sessionsDir as agentDir/sessions", () => {
29
- const paths = computeExtensionPaths("/test/agent");
30
- expect(paths.sessionsDir).toBe("/test/agent/sessions");
31
- });
32
-
33
- it("derives subagentSessionsDir as agentDir/subagent-sessions", () => {
34
- const paths = computeExtensionPaths("/test/agent");
35
- expect(paths.subagentSessionsDir).toBe("/test/agent/subagent-sessions");
36
- });
37
-
38
- it("derives forwardingDir as sessionsDir/permission-forwarding", () => {
39
- const paths = computeExtensionPaths("/test/agent");
40
- expect(paths.forwardingDir).toBe(
41
- join("/test/agent/sessions", "permission-forwarding"),
42
- );
43
- });
44
-
45
- it("derives globalLogsDir via getGlobalLogsDir(agentDir)", () => {
46
- const paths = computeExtensionPaths("/test/agent");
47
- expect(paths.globalLogsDir).toBe(getGlobalLogsDir("/test/agent"));
48
- });
49
-
50
- it("includes agentDir in piInfrastructureDirs", () => {
51
- const paths = computeExtensionPaths("/test/agent");
52
- expect(paths.piInfrastructureDirs).toContain("/test/agent");
53
- });
54
-
55
- it("includes agentDir/git in piInfrastructureDirs", () => {
56
- const paths = computeExtensionPaths("/test/agent");
57
- expect(paths.piInfrastructureDirs).toContain("/test/agent/git");
58
- });
59
-
60
- it("includes discovered global node_modules root in piInfrastructureDirs", () => {
61
- const paths = computeExtensionPaths("/test/agent");
62
- expect(paths.piInfrastructureDirs).toContain("/mock/global/node_modules");
63
- });
64
-
65
- it("omits global node_modules from piInfrastructureDirs when discovery returns null", () => {
66
- mockDiscoverGlobalNodeModulesRoot.mockReturnValue(null);
67
- const paths = computeExtensionPaths("/test/agent");
68
- expect(paths.piInfrastructureDirs).toHaveLength(2);
69
- expect(paths.piInfrastructureDirs).toContain("/test/agent");
70
- expect(paths.piInfrastructureDirs).toContain("/test/agent/git");
71
- });
72
-
73
- it("all entries in piInfrastructureDirs are strings (no null)", () => {
74
- mockDiscoverGlobalNodeModulesRoot.mockReturnValue(null);
75
- const paths = computeExtensionPaths("/test/agent");
76
- for (const dir of paths.piInfrastructureDirs) {
77
- expect(typeof dir).toBe("string");
78
- }
79
- });
80
-
81
- it("includes piPackageDir in piInfrastructureDirs when provided", () => {
82
- const paths = computeExtensionPaths("/test/agent", "/pi/install");
83
- expect(paths.piInfrastructureDirs).toContain("/pi/install");
84
- });
85
-
86
- it("omits piPackageDir when not provided (current behavior preserved)", () => {
87
- const paths = computeExtensionPaths("/test/agent");
88
- expect(paths.piInfrastructureDirs).toEqual([
89
- "/test/agent",
90
- "/test/agent/git",
91
- "/mock/global/node_modules",
92
- ]);
93
- });
94
-
95
- it("omits piPackageDir when given an empty string", () => {
96
- const paths = computeExtensionPaths("/test/agent", "");
97
- expect(paths.piInfrastructureDirs).not.toContain("");
98
- });
99
-
100
- it("two calls with different agentDirs produce independent results", () => {
101
- const a = computeExtensionPaths("/agent/a");
102
- const b = computeExtensionPaths("/agent/b");
103
- expect(a.agentDir).toBe("/agent/a");
104
- expect(b.agentDir).toBe("/agent/b");
105
- expect(a.sessionsDir).toBe("/agent/a/sessions");
106
- expect(b.sessionsDir).toBe("/agent/b/sessions");
107
- });
108
- });
@@ -1,251 +0,0 @@
1
- import {
2
- existsSync,
3
- mkdirSync,
4
- mkdtempSync,
5
- rmSync,
6
- writeFileSync,
7
- } from "node:fs";
8
- import { tmpdir } from "node:os";
9
- import { join } from "node:path";
10
-
11
- import { afterEach, describe, expect, it, vi } from "vitest";
12
-
13
- import {
14
- cleanupPermissionForwardingLocationIfEmpty,
15
- formatUnknownErrorMessage,
16
- isErrnoCode,
17
- logPermissionForwardingError,
18
- logPermissionForwardingWarning,
19
- tryRemoveDirectoryIfEmpty,
20
- } from "#src/forwarded-permissions/io";
21
- import { createPermissionForwardingLocation } from "#src/permission-forwarding";
22
- import type { DebugReviewLogger } from "#src/session-logger";
23
-
24
- // ── helpers ────────────────────────────────────────────────────────────────
25
-
26
- function makeLogger(): DebugReviewLogger {
27
- return {
28
- review: vi.fn(),
29
- debug: vi.fn(),
30
- };
31
- }
32
-
33
- // ── formatUnknownErrorMessage ──────────────────────────────────────────────
34
-
35
- describe("formatUnknownErrorMessage", () => {
36
- it("returns the error message for Error instances", () => {
37
- expect(formatUnknownErrorMessage(new Error("oops"))).toBe("oops");
38
- });
39
-
40
- it("converts non-Error values to string", () => {
41
- expect(formatUnknownErrorMessage("raw string")).toBe("raw string");
42
- expect(formatUnknownErrorMessage(42)).toBe("42");
43
- });
44
-
45
- it("falls back to String(error) for Error with empty message", () => {
46
- // error.message is falsy (""), so the function falls through to String(error)
47
- const e = new Error("");
48
- expect(formatUnknownErrorMessage(e)).toBe("Error");
49
- });
50
- });
51
-
52
- // ── isErrnoCode ────────────────────────────────────────────────────────────
53
-
54
- describe("isErrnoCode", () => {
55
- it("returns true when code matches", () => {
56
- expect(isErrnoCode({ code: "ENOENT" }, "ENOENT")).toBe(true);
57
- });
58
-
59
- it("returns false when code does not match", () => {
60
- expect(isErrnoCode({ code: "EACCES" }, "ENOENT")).toBe(false);
61
- });
62
-
63
- it("returns false for null", () => {
64
- expect(isErrnoCode(null, "ENOENT")).toBe(false);
65
- });
66
-
67
- it("returns false when no code property", () => {
68
- expect(isErrnoCode({}, "ENOENT")).toBe(false);
69
- });
70
- });
71
-
72
- // ── logPermissionForwardingWarning ─────────────────────────────────────────
73
-
74
- describe("logPermissionForwardingWarning", () => {
75
- it("calls logger.review with the warning event", () => {
76
- const logger = makeLogger();
77
- logPermissionForwardingWarning(logger, "something went wrong");
78
- expect(logger.review).toHaveBeenCalledWith(
79
- "permission_forwarding.warning",
80
- { message: "something went wrong" },
81
- );
82
- });
83
-
84
- it("calls logger.debug with the warning event", () => {
85
- const logger = makeLogger();
86
- logPermissionForwardingWarning(logger, "something went wrong");
87
- expect(logger.debug).toHaveBeenCalledWith("permission_forwarding.warning", {
88
- message: "something went wrong",
89
- });
90
- });
91
-
92
- it("includes formatted error when an error is provided", () => {
93
- const logger = makeLogger();
94
- logPermissionForwardingWarning(logger, "bad thing", new Error("fs fail"));
95
- expect(logger.review).toHaveBeenCalledWith(
96
- "permission_forwarding.warning",
97
- { message: "bad thing", error: "fs fail" },
98
- );
99
- });
100
-
101
- it("does not throw when logger is null", () => {
102
- expect(() => logPermissionForwardingWarning(null, "ignored")).not.toThrow();
103
- });
104
-
105
- it("does not call anything when logger is null", () => {
106
- // Verify the null-logger path is a true no-op — cannot easily spy on null,
107
- // but we can verify the call succeeds silently.
108
- expect(() =>
109
- logPermissionForwardingWarning(null, "msg", new Error("err")),
110
- ).not.toThrow();
111
- });
112
- });
113
-
114
- // ── logPermissionForwardingError ───────────────────────────────────────────
115
-
116
- describe("logPermissionForwardingError", () => {
117
- it("calls logger.review with the error event", () => {
118
- const logger = makeLogger();
119
- logPermissionForwardingError(logger, "critical failure");
120
- expect(logger.review).toHaveBeenCalledWith("permission_forwarding.error", {
121
- message: "critical failure",
122
- });
123
- });
124
-
125
- it("calls logger.debug with the error event", () => {
126
- const logger = makeLogger();
127
- logPermissionForwardingError(logger, "critical failure");
128
- expect(logger.debug).toHaveBeenCalledWith("permission_forwarding.error", {
129
- message: "critical failure",
130
- });
131
- });
132
-
133
- it("includes formatted error when an error is provided", () => {
134
- const logger = makeLogger();
135
- logPermissionForwardingError(logger, "io error", new Error("ENOENT"));
136
- expect(logger.review).toHaveBeenCalledWith("permission_forwarding.error", {
137
- message: "io error",
138
- error: "ENOENT",
139
- });
140
- });
141
-
142
- it("does not throw when logger is null", () => {
143
- expect(() => logPermissionForwardingError(null, "ignored")).not.toThrow();
144
- });
145
- });
146
-
147
- // ── tryRemoveDirectoryIfEmpty ──────────────────────────────────────────────
148
-
149
- describe("tryRemoveDirectoryIfEmpty", () => {
150
- let root: string;
151
-
152
- afterEach(() => {
153
- rmSync(root, { recursive: true, force: true });
154
- });
155
-
156
- it("returns true when the directory does not exist", () => {
157
- root = mkdtempSync(join(tmpdir(), "io-test-"));
158
- const absent = join(root, "nonexistent");
159
- expect(tryRemoveDirectoryIfEmpty(null, absent, "test")).toBe(true);
160
- });
161
-
162
- it("returns true and removes an empty directory", () => {
163
- root = mkdtempSync(join(tmpdir(), "io-test-"));
164
- const dir = join(root, "empty");
165
- mkdirSync(dir);
166
- expect(tryRemoveDirectoryIfEmpty(null, dir, "test")).toBe(true);
167
- expect(existsSync(dir)).toBe(false);
168
- });
169
-
170
- it("returns false and leaves a non-empty directory in place", () => {
171
- root = mkdtempSync(join(tmpdir(), "io-test-"));
172
- const dir = join(root, "nonempty");
173
- mkdirSync(dir);
174
- writeFileSync(join(dir, "file.json"), "{}", "utf-8");
175
- expect(tryRemoveDirectoryIfEmpty(null, dir, "test")).toBe(false);
176
- expect(existsSync(dir)).toBe(true);
177
- });
178
- });
179
-
180
- // ── cleanupPermissionForwardingLocationIfEmpty ─────────────────────────────
181
-
182
- describe("cleanupPermissionForwardingLocationIfEmpty", () => {
183
- let root: string;
184
-
185
- afterEach(() => {
186
- rmSync(root, { recursive: true, force: true });
187
- });
188
-
189
- it("preserves responses/ when requests/ is non-empty (the concurrent-request race)", () => {
190
- root = mkdtempSync(join(tmpdir(), "io-cleanup-"));
191
- const forwardingDir = join(root, "forwarding");
192
- const location = createPermissionForwardingLocation(
193
- forwardingDir,
194
- "parent-session",
195
- );
196
- // Simulate: requests/ has a pending file, responses/ is momentarily empty
197
- mkdirSync(location.requestsDir, { recursive: true });
198
- mkdirSync(location.responsesDir, { recursive: true });
199
- writeFileSync(join(location.requestsDir, "req-b.json"), "{}", "utf-8");
200
- // responses/ is empty (sibling subagent A already cleaned up its response)
201
-
202
- cleanupPermissionForwardingLocationIfEmpty(null, location);
203
-
204
- // requests/ is non-empty → should NOT be removed
205
- expect(existsSync(location.requestsDir)).toBe(true);
206
- // responses/ must survive — removing it causes the ENOENT write loop
207
- expect(existsSync(location.responsesDir)).toBe(true);
208
- // sessionRoot must also survive while subdirs are present
209
- expect(existsSync(location.sessionRootDir)).toBe(true);
210
- });
211
-
212
- it("removes both subdirs and sessionRoot when both are empty (normal serial cleanup)", () => {
213
- root = mkdtempSync(join(tmpdir(), "io-cleanup-"));
214
- const forwardingDir = join(root, "forwarding");
215
- const location = createPermissionForwardingLocation(
216
- forwardingDir,
217
- "parent-session",
218
- );
219
- mkdirSync(location.requestsDir, { recursive: true });
220
- mkdirSync(location.responsesDir, { recursive: true });
221
- // Both empty — normal end-of-lifecycle state
222
-
223
- cleanupPermissionForwardingLocationIfEmpty(null, location);
224
-
225
- expect(existsSync(location.requestsDir)).toBe(false);
226
- expect(existsSync(location.responsesDir)).toBe(false);
227
- expect(existsSync(location.sessionRootDir)).toBe(false);
228
- });
229
-
230
- it("leaves responses/ in place when it is non-empty even if requests/ is empty", () => {
231
- root = mkdtempSync(join(tmpdir(), "io-cleanup-"));
232
- const forwardingDir = join(root, "forwarding");
233
- const location = createPermissionForwardingLocation(
234
- forwardingDir,
235
- "parent-session",
236
- );
237
- mkdirSync(location.requestsDir, { recursive: true });
238
- mkdirSync(location.responsesDir, { recursive: true });
239
- writeFileSync(join(location.responsesDir, "resp.json"), "{}", "utf-8");
240
- // requests/ is empty, responses/ has a stale response
241
-
242
- cleanupPermissionForwardingLocationIfEmpty(null, location);
243
-
244
- // requests/ is empty so it gets removed
245
- expect(existsSync(location.requestsDir)).toBe(false);
246
- // responses/ is non-empty → survives
247
- expect(existsSync(location.responsesDir)).toBe(true);
248
- // sessionRoot survives because responses/ is still present
249
- expect(existsSync(location.sessionRootDir)).toBe(true);
250
- });
251
- });