claude-code-session-manager 0.140.0 → 0.142.0

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 (204) hide show
  1. package/README.md +80 -70
  2. package/bin/cli.cjs +11 -0
  3. package/dist/assets/AppSettings-BcZgIvvY.js +2 -0
  4. package/dist/assets/{History--JwsFnbn.js → History-DpZuJXi1.js} +1 -1
  5. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +3 -0
  6. package/dist/assets/{Panel-CALyU0pe.js → Panel-BjdJjhqt.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BTClYV6i.js} +7 -7
  8. package/dist/assets/Scheduler-DPobKx1Z.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Cqyu4mef.js} +1 -1
  10. package/dist/assets/{Skills-DtRzghn5.js → Skills-vv0noNVI.js} +5 -5
  11. package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-CXi8Pvut.js} +1 -1
  12. package/dist/assets/Toggle-CiYCWLjh.js +1 -0
  13. package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-4NKKd1sC.js} +1 -1
  14. package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-DDunb8Ch.js} +1 -1
  15. package/dist/assets/index-Cn5E9958.js +3133 -0
  16. package/dist/assets/{index-DKXdXfka.css → index-DVHIHoJf.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +496 -484
  20. package/package.json +4 -2
  21. package/plugins/AGENTS.md +4 -3
  22. package/plugins/session-manager-dev/hooks/hooks.json +15 -0
  23. package/plugins/session-manager-dev/hooks/residue-check.cjs +241 -0
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  25. package/plugins/session-manager-dev/skills/develop/SKILL.md +55 -18
  26. package/plugins/session-manager-dev/skills/develop/standards.md +3 -2
  27. package/scripts/README.md +1 -0
  28. package/scripts/hooks/guard-tool-risk.cjs +5 -1
  29. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +158 -1
  30. package/scripts/scheduler-mcp-server.cjs +737 -110
  31. package/src/main/adminRouteRegistry.cjs +59 -0
  32. package/src/main/agentLibrary.cjs +72 -4
  33. package/src/main/agentsIpc.cjs +3 -2
  34. package/src/main/build-info.json +4 -4
  35. package/src/main/chatRunner.cjs +231 -16
  36. package/src/main/config.cjs +30 -0
  37. package/src/main/docEdit.cjs +4 -2
  38. package/src/main/health.cjs +91 -0
  39. package/src/main/index.cjs +98 -48
  40. package/src/main/ipcSchemas.cjs +171 -8
  41. package/src/main/lib/AGENTS.md +1 -1
  42. package/src/main/lib/chatBootRecovery.cjs +2 -0
  43. package/src/main/lib/claude/agentModelResolve.cjs +51 -25
  44. package/src/main/lib/claude/agentSnapshot.cjs +186 -0
  45. package/src/main/lib/claude/environmentProfiles.cjs +242 -0
  46. package/src/main/lib/claude/jobSandboxPolicy.cjs +241 -33
  47. package/src/main/lib/claude/personaToolScope.cjs +82 -31
  48. package/src/main/lib/claude/runClaudeP.cjs +4 -2
  49. package/src/main/lib/claude/toolRiskMarks.cjs +41 -1
  50. package/src/main/lib/claude/usageCircuit.cjs +49 -21
  51. package/src/main/lib/claude/vaultRefs.cjs +277 -0
  52. package/src/main/lib/demo-video-kit/capture.cjs +282 -12
  53. package/src/main/lib/demo-video-kit/cast.md +43 -0
  54. package/src/main/lib/demo-video-kit/character.cjs +722 -30
  55. package/src/main/lib/demo-video-kit/checks.cjs +120 -1
  56. package/src/main/lib/demo-video-kit/export.cjs +218 -0
  57. package/src/main/lib/demo-video-kit/frames.cjs +104 -9
  58. package/src/main/lib/demo-video-kit/kind-marketing.md +121 -0
  59. package/src/main/lib/demo-video-kit/kind-tiktok.md +99 -0
  60. package/src/main/lib/demo-video-kit/kokoroSay.cjs +205 -0
  61. package/src/main/lib/demo-video-kit/project-home-html.md +43 -0
  62. package/src/main/lib/demo-video-kit/resumableRun.cjs +298 -0
  63. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  64. package/src/main/lib/demo-video-kit/voiceLane.cjs +233 -0
  65. package/src/main/lib/demo-video-kit/voiceLibrary.cjs +312 -0
  66. package/src/main/lib/epic/artifactAdminRoutes.cjs +211 -0
  67. package/src/main/lib/epic/artifactIpc.cjs +153 -0
  68. package/src/main/lib/epic/artifactNotice.cjs +72 -0
  69. package/src/main/lib/epic/artifactRetention.cjs +310 -0
  70. package/src/main/lib/epic/artifactStore.cjs +392 -0
  71. package/src/main/lib/epic/delegationReadiness.cjs +76 -2
  72. package/src/main/lib/epic/epicAgentRefresh.cjs +97 -0
  73. package/src/main/lib/epic/epicEventLog.cjs +214 -0
  74. package/src/main/lib/epic/epicMint.cjs +43 -1
  75. package/src/main/lib/epic/epicOutsideRead.cjs +1 -0
  76. package/src/main/lib/epic/epicOutsideState.cjs +18 -4
  77. package/src/main/lib/epic/epicPurge.cjs +347 -0
  78. package/src/main/lib/epic/epicReopen.cjs +5 -2
  79. package/src/main/lib/epic/epicSettle.cjs +4 -13
  80. package/src/main/lib/epic/epicSpawnPlan.cjs +57 -4
  81. package/src/main/lib/epic/epicStatusMirror.cjs +34 -1
  82. package/src/main/lib/epic/epicTransitions.cjs +139 -0
  83. package/src/main/lib/epic/epicValidationHook.cjs +81 -2
  84. package/src/main/lib/epic/guardSpawnSettings.cjs +3 -2
  85. package/src/main/lib/externalContract.cjs +37 -4
  86. package/src/main/lib/feedback-remote/crossProjectReply.cjs +389 -126
  87. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -3
  88. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +11 -6
  89. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +26 -1
  90. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +5 -2
  91. package/src/main/lib/feedback-remote/feedbackBoxDrain.cjs +409 -0
  92. package/src/main/lib/feedback-remote/feedbackBoxKeys.cjs +218 -0
  93. package/src/main/lib/feedback-remote/feedbackEnvelope.cjs +163 -0
  94. package/src/main/lib/feedback-remote/feedbackRelayClient.cjs +164 -0
  95. package/src/main/lib/feedback-remote/feedbackReport.cjs +234 -0
  96. package/src/main/lib/feedback-remote/feedbackSeal.cjs +217 -0
  97. package/src/main/lib/feedback-remote/localAdminHttp.cjs +108 -2
  98. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +2 -1
  99. package/src/main/lib/feedback-remote/needsYouIpc.cjs +17 -0
  100. package/src/main/lib/feedback-remote/needsYouStore.cjs +177 -6
  101. package/src/main/lib/feedback-remote/pendingReplies.cjs +189 -0
  102. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +188 -10
  103. package/src/main/lib/feedback-remote/serviceClient.cjs +429 -0
  104. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +252 -0
  105. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +284 -0
  106. package/src/main/lib/feedback-remote/servicePairings.cjs +313 -0
  107. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +290 -0
  108. package/src/main/lib/feedback-remote/siteFeedbackAdminRoutes.cjs +295 -0
  109. package/src/main/lib/feedback-remote/siteFeedbackInbox.cjs +598 -0
  110. package/src/main/lib/feedback-remote/siteFeedbackIpc.cjs +86 -0
  111. package/src/main/lib/feedback-remote/siteFeedbackService.cjs +477 -0
  112. package/src/main/lib/git/worktreeDeps.cjs +77 -2
  113. package/src/main/lib/mcpToolCatalog.cjs +315 -30
  114. package/src/main/lib/opsOwnership.cjs +29 -1
  115. package/src/main/lib/opsRetentionSettings.cjs +27 -5
  116. package/src/main/lib/persona-macro/builtinMacros.cjs +7 -2
  117. package/src/main/lib/persona-macro/macroJobDispatch.cjs +52 -8
  118. package/src/main/lib/persona-macro/macroJobIpc.cjs +16 -6
  119. package/src/main/lib/persona-macro/macroLibrary.cjs +49 -7
  120. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +83 -0
  121. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +3 -0
  122. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +263 -0
  123. package/src/main/lib/phaseProjection.cjs +103 -0
  124. package/src/main/lib/prd/depSlugResolve.cjs +4 -13
  125. package/src/main/lib/prd/prdBodyPatch.cjs +12 -17
  126. package/src/main/lib/prd/prdCreate.cjs +67 -5
  127. package/src/main/lib/prd/prdCriteria.cjs +225 -0
  128. package/src/main/lib/prd/prdFrontmatter.cjs +68 -3
  129. package/src/main/lib/prd/prdGateFiles.cjs +125 -49
  130. package/src/main/lib/prd/prdSizing.cjs +3 -1
  131. package/src/main/lib/process/cleanEnv.cjs +52 -1
  132. package/src/main/lib/process/leftoverRenice.cjs +178 -0
  133. package/src/main/lib/process/memoryScope.cjs +31 -3
  134. package/src/main/lib/project-pages/pagesLibrary.cjs +72 -6
  135. package/src/main/lib/project-pages/videoReviewIpc.cjs +3 -2
  136. package/src/main/lib/project-pages/voiceAdminRoutes.cjs +175 -0
  137. package/src/main/lib/project-pages/voicePreview.cjs +196 -0
  138. package/src/main/lib/project-pages/voicesIpc.cjs +186 -0
  139. package/src/main/lib/promptSessionSchema.cjs +6 -0
  140. package/src/main/lib/scheduler/cancelledRow.cjs +57 -0
  141. package/src/main/lib/scheduler/cpuSample.cjs +133 -42
  142. package/src/main/lib/scheduler/criteriaChecks.cjs +169 -0
  143. package/src/main/lib/scheduler/definitionOfDone.cjs +44 -5
  144. package/src/main/lib/scheduler/jobMemoryStats.cjs +313 -0
  145. package/src/main/lib/scheduler/loadGate.cjs +82 -4
  146. package/src/main/lib/scheduler/planRecordHarvest.cjs +32 -2
  147. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +133 -0
  148. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  149. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  150. package/src/main/lib/scheduler/runLogRetention.cjs +42 -1
  151. package/src/main/lib/scheduler/scheduleJobSchema.cjs +5 -0
  152. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +47 -0
  153. package/src/main/lib/scheduler/schedulerConfig.cjs +47 -0
  154. package/src/main/lib/scheduler/schedulerPaths.cjs +0 -3
  155. package/src/main/lib/scheduler/schedulerRuntimeState.cjs +50 -1
  156. package/src/main/lib/scheduler/sessionSlots.cjs +5 -1
  157. package/src/main/lib/scheduler/slotsRoute.cjs +237 -0
  158. package/src/main/lib/scheduler/toolClearance.cjs +258 -0
  159. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +140 -10
  160. package/src/main/lib/tasks/memoryConsolidation.cjs +300 -0
  161. package/src/main/lib/tasks/mitigationReview.cjs +294 -0
  162. package/src/main/lib/tasks/taskAdminRoutes.cjs +312 -22
  163. package/src/main/lib/tasks/taskIpc.cjs +22 -18
  164. package/src/main/lib/tasks/taskLedger.cjs +147 -25
  165. package/src/main/lib/tasks/taskRun.cjs +186 -17
  166. package/src/main/lib/tasks/taskSwitch.cjs +85 -12
  167. package/src/main/lib/tasks/taskSwitchRoute.cjs +172 -0
  168. package/src/main/lib/telemetry/auditEvents.cjs +207 -6
  169. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +198 -6
  170. package/src/main/lib/telemetry/webhookDelivery.cjs +205 -0
  171. package/src/main/lib/telemetry/webhookRegistry.cjs +281 -0
  172. package/src/main/lib/toolUseClassify.cjs +181 -0
  173. package/src/main/lib/util/smfileRange.cjs +77 -0
  174. package/src/main/projectPages.cjs +3 -1
  175. package/src/main/promptSessionEvents.cjs +5 -0
  176. package/src/main/pty.cjs +68 -0
  177. package/src/main/queueOps.cjs +32 -13
  178. package/src/main/runVerify.cjs +74 -9
  179. package/src/main/scheduler/AGENTS.md +1 -0
  180. package/src/main/scheduler/budget.cjs +6 -5
  181. package/src/main/scheduler/prdParser.cjs +62 -14
  182. package/src/main/scheduler/reviewLadder.cjs +45 -28
  183. package/src/main/scheduler/starvation.cjs +69 -0
  184. package/src/main/scheduler/utilizationHold.cjs +101 -0
  185. package/src/main/scheduler.cjs +1745 -210
  186. package/src/main/templates/PRD_AUTHORING.md +13 -2
  187. package/src/main/webRemote.cjs +463 -6
  188. package/src/preload/api.d.ts +529 -38
  189. package/src/preload/apiSurface.json +209 -7
  190. package/src/preload/index.cjs +46 -1
  191. package/src/seed/agents/architect.md +6 -1
  192. package/src/seed/agents/blender-artist.md +2 -1
  193. package/src/seed/agents/competitive-analyst.md +3 -1
  194. package/src/seed/agents/competitive-researcher.md +2 -1
  195. package/src/seed/agents/demo-video-builder.md +87 -83
  196. package/src/seed/agents/dev-lead.md +3 -3
  197. package/src/seed/agents/project-home-builder.md +9 -31
  198. package/src/seed/agents/validator.md +9 -10
  199. package/dist/assets/AppSettings-CMFEM68R.js +0 -2
  200. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +0 -3
  201. package/dist/assets/Scheduler-YT3j8SUa.js +0 -16
  202. package/dist/assets/ViewTabs-B7qLXRAH.js +0 -1
  203. package/dist/assets/index-CtxruO1L.js +0 -3121
  204. package/src/main/lib/epic/epicStateWatcher.cjs +0 -157
@@ -0,0 +1,242 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * environmentProfiles.cjs — declared environment profiles (Managed Agents'
5
+ * "environment" primitive, kept local).
6
+ *
7
+ * An environment states what a headless run may touch:
8
+ * - osSandboxRequired: whether the OS sandbox (bwrap+socat / sandbox-exec) is required
9
+ * - permissionMode: the CLI --permission-mode under the OS sandbox
10
+ * - writeRoots: write roots; each is absolute or starts with a token
11
+ * {worktree} / {projectRoot} / {home} / {tmp}
12
+ * - network: { mode: 'none' } | { mode: 'allowlist', hosts } | { mode: 'open' }
13
+ * - secretDenyPaths: home-relative paths no tool may read or write
14
+ * - webFetch / webSearch: whether those tools are allowed
15
+ * - credentials (optional): [{ ref, server, envVar }] local vault refs
16
+ * (vaultRefs.cjs) resolved only into that MCP server's
17
+ * spawn env, never the job env
18
+ *
19
+ * Resolution for a name (first hit wins, whole-file replace, no merging):
20
+ * <project>/.claude/environments/<name>.json
21
+ * ~/.claude/session-manager/environments/<name>.json
22
+ * the built-ins below (headless-default, validator-readonly, open-web)
23
+ * A file that exists but fails the zod-strict schema (or is not JSON) is
24
+ * REFUSED ('environment_invalid') — never silently skipped to a lower layer.
25
+ * A name found nowhere is refused as 'environment_unknown'.
26
+ *
27
+ * Personas reference one by `environment:` frontmatter; absent = DEFAULT_ENVIRONMENT.
28
+ * The built-ins carry the sandbox settings jobSandboxPolicy.cjs applies by
29
+ * default (validator → validator-readonly, dev-lead → headless-default, via
30
+ * its LEGACY_PERSONA_ENVIRONMENTS); toSandboxProfile maps a profile onto a
31
+ * { permissionMode, network } shape.
32
+ *
33
+ * hash = sha256 of the profile's canonical JSON (agentSnapshot.cjs's canonicalJson),
34
+ * so key order is irrelevant and any edit changes it.
35
+ *
36
+ * Local files only; read-only (no writer here).
37
+ */
38
+
39
+ const fs = require('node:fs');
40
+ const os = require('node:os');
41
+ const path = require('node:path');
42
+ const crypto = require('node:crypto');
43
+ const { z } = require('zod');
44
+ const { SANDBOX_SECRET_PATHS } = require('./jobSandboxPolicy.cjs');
45
+ const { canonicalJson } = require('./agentSnapshot.cjs');
46
+ const { isVaultRef } = require('./vaultRefs.cjs');
47
+
48
+ const DEFAULT_ENVIRONMENT = 'headless-default';
49
+ const ENV_NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
50
+ const ROOT_TOKEN_RE = /^\{(worktree|projectRoot|home|tmp)\}(\/.*)?$/;
51
+
52
+ const HostSchema = z.string().trim().min(1).regex(/^[A-Za-z0-9*.-]+$/, 'host must be a domain name (wildcards allowed)');
53
+
54
+ const NetworkSchema = z.discriminatedUnion('mode', [
55
+ z.object({ mode: z.literal('none') }).strict(),
56
+ z.object({ mode: z.literal('allowlist'), hosts: z.array(HostSchema).min(1) }).strict(),
57
+ z.object({ mode: z.literal('open') }).strict(),
58
+ ]);
59
+
60
+ const WriteRootSchema = z
61
+ .string()
62
+ .min(1)
63
+ .refine((v) => ROOT_TOKEN_RE.test(v) || path.isAbsolute(v), 'write root must be absolute or start with {worktree}/{projectRoot}/{home}/{tmp}');
64
+
65
+ const SecretPathSchema = z
66
+ .string()
67
+ .min(1)
68
+ .refine((v) => !path.isAbsolute(v) && !v.split('/').includes('..'), 'secret deny path must be home-relative');
69
+
70
+ /**
71
+ * One local vault credential (vaultRefs.cjs): `ref` resolves only into the
72
+ * spawn env of MCP server `server` (which must run outside the job, checked at
73
+ * spawn by assertRefTargetsServer) as `envVar` — never into the job env.
74
+ */
75
+ const CredentialSchema = z
76
+ .object({
77
+ ref: z.string().min(1).refine(isVaultRef, 'ref must be keyring:<service>/<account> or file:<path under a vault root>[#KEY]'),
78
+ server: z.string().trim().min(1),
79
+ envVar: z.string().regex(/^[A-Z_][A-Z0-9_]*$/, 'envVar must look like API_TOKEN'),
80
+ })
81
+ .strict();
82
+
83
+ const EnvironmentProfileSchema = z
84
+ .object({
85
+ description: z.string().optional(),
86
+ osSandboxRequired: z.boolean(),
87
+ permissionMode: z.enum(['default', 'acceptEdits', 'plan', 'bypassPermissions']),
88
+ writeRoots: z.array(WriteRootSchema),
89
+ network: NetworkSchema,
90
+ secretDenyPaths: z.array(SecretPathSchema),
91
+ webFetch: z.boolean(),
92
+ webSearch: z.boolean(),
93
+ credentials: z.array(CredentialSchema).optional(),
94
+ })
95
+ .strict();
96
+
97
+ /** jobSandboxPolicy.cjs's os-sandbox allowWrite list, as tokens. */
98
+ const JOB_WRITE_ROOTS = Object.freeze([
99
+ '{worktree}',
100
+ '{projectRoot}/.git',
101
+ '{tmp}',
102
+ '{home}/.npm',
103
+ '{home}/.cache',
104
+ '{projectRoot}/node_modules/.vite',
105
+ '{projectRoot}/node_modules/.vitest',
106
+ ]);
107
+
108
+ const deepFreeze = (o) => {
109
+ for (const v of Object.values(o)) if (v && typeof v === 'object') deepFreeze(v);
110
+ return Object.freeze(o);
111
+ };
112
+
113
+ const BUILTIN_ENVIRONMENTS = deepFreeze({
114
+ 'headless-default': {
115
+ description: 'OS sandbox + network allow-list (dev-lead today).',
116
+ osSandboxRequired: true,
117
+ permissionMode: 'acceptEdits',
118
+ writeRoots: [...JOB_WRITE_ROOTS],
119
+ network: { mode: 'allowlist', hosts: ['registry.npmjs.org'] },
120
+ secretDenyPaths: [...SANDBOX_SECRET_PATHS],
121
+ webFetch: false,
122
+ webSearch: false,
123
+ },
124
+ 'validator-readonly': {
125
+ description: 'OS sandbox, no network, default permission mode (validator today).',
126
+ osSandboxRequired: true,
127
+ permissionMode: 'default',
128
+ writeRoots: [...JOB_WRITE_ROOTS],
129
+ network: { mode: 'none' },
130
+ secretDenyPaths: [...SANDBOX_SECRET_PATHS],
131
+ webFetch: false,
132
+ webSearch: false,
133
+ },
134
+ 'open-web': {
135
+ description: 'Open network with WebFetch/WebSearch; OS sandbox not required.',
136
+ osSandboxRequired: false,
137
+ permissionMode: 'acceptEdits',
138
+ writeRoots: [...JOB_WRITE_ROOTS],
139
+ network: { mode: 'open' },
140
+ secretDenyPaths: [...SANDBOX_SECRET_PATHS],
141
+ webFetch: true,
142
+ webSearch: true,
143
+ },
144
+ });
145
+
146
+ const sha256 = (s) => crypto.createHash('sha256').update(String(s)).digest('hex');
147
+
148
+ /** Content hash of a profile (canonical JSON, key order irrelevant). */
149
+ function environmentHash(profile) {
150
+ return sha256(canonicalJson(profile));
151
+ }
152
+
153
+ /** @param {{ cwd?: string, homeDir?: string }} o */
154
+ function environmentFiles(name, { cwd, homeDir } = {}) {
155
+ const home = homeDir || os.homedir();
156
+ const files = [];
157
+ if (typeof cwd === 'string' && cwd) files.push({ source: 'project', file: path.join(cwd, '.claude', 'environments', `${name}.json`) });
158
+ files.push({ source: 'global', file: path.join(home, '.claude', 'session-manager', 'environments', `${name}.json`) });
159
+ return files;
160
+ }
161
+
162
+ function zodErrors(error) {
163
+ return error.issues.map((issue) => {
164
+ if (issue.code === 'unrecognized_keys') return `unknown key(s): ${issue.keys.join(', ')}`;
165
+ return `${issue.path.length ? issue.path.join('.') : '(profile)'}: ${issue.message}`;
166
+ });
167
+ }
168
+
169
+ /**
170
+ * Resolve environment `name` (default headless-default) for project `cwd`.
171
+ * @param {{ cwd?: string, name?: string|null, homeDir?: string }} opts
172
+ * @returns {{ id: string, hash: string, profile: object, source: 'project'|'global'|'builtin', file: string|null }
173
+ * | { code: 'environment_unknown', name: string }
174
+ * | { code: 'environment_invalid', name: string, file: string, errors: string[] }}
175
+ */
176
+ function loadEnvironment({ cwd, name, homeDir } = {}) {
177
+ const id = name === undefined || name === null || name === '' ? DEFAULT_ENVIRONMENT : String(name);
178
+ if (!ENV_NAME_RE.test(id)) return { code: 'environment_unknown', name: id };
179
+
180
+ for (const { source, file } of environmentFiles(id, { cwd, homeDir })) {
181
+ let text;
182
+ try {
183
+ text = fs.readFileSync(file, 'utf8');
184
+ } catch (e) {
185
+ if (e && e.code === 'ENOENT') continue;
186
+ return { code: 'environment_invalid', name: id, file, errors: [`unreadable: ${e && e.message}`] };
187
+ }
188
+ let raw;
189
+ try {
190
+ raw = JSON.parse(text);
191
+ } catch (e) {
192
+ return { code: 'environment_invalid', name: id, file, errors: [`not JSON: ${e && e.message}`] };
193
+ }
194
+ const parsed = EnvironmentProfileSchema.safeParse(raw);
195
+ if (!parsed.success) return { code: 'environment_invalid', name: id, file, errors: zodErrors(parsed.error) };
196
+ return { id, hash: environmentHash(parsed.data), profile: parsed.data, source, file };
197
+ }
198
+
199
+ if (Object.prototype.hasOwnProperty.call(BUILTIN_ENVIRONMENTS, id)) {
200
+ const profile = BUILTIN_ENVIRONMENTS[id];
201
+ return { id, hash: environmentHash(profile), profile, source: 'builtin', file: null };
202
+ }
203
+ return { code: 'environment_unknown', name: id };
204
+ }
205
+
206
+ /**
207
+ * A profile as { permissionMode, network }. network: the
208
+ * allow-list hosts ([] for 'none'), or null for 'open' (no allow-list).
209
+ * @returns {{ permissionMode: string, network: string[]|null }}
210
+ */
211
+ function toSandboxProfile(profile) {
212
+ const n = profile.network;
213
+ return {
214
+ permissionMode: profile.permissionMode,
215
+ network: n.mode === 'open' ? null : n.mode === 'allowlist' ? [...n.hosts] : [],
216
+ };
217
+ }
218
+
219
+ /**
220
+ * Absolute write roots for a job, tokens substituted.
221
+ * @param {{ writeRoots: string[] }} profile
222
+ * @param {{ worktreeDir: string, projectRoot: string, homeDir: string, tmpDir: string }} dirs
223
+ */
224
+ function expandWriteRoots(profile, { worktreeDir, projectRoot, homeDir, tmpDir }) {
225
+ const base = { worktree: worktreeDir, projectRoot, home: homeDir, tmp: tmpDir };
226
+ return profile.writeRoots.map((r) => {
227
+ const m = r.match(ROOT_TOKEN_RE);
228
+ return m ? path.join(base[m[1]], m[2] || '') : r;
229
+ });
230
+ }
231
+
232
+ module.exports = {
233
+ DEFAULT_ENVIRONMENT,
234
+ BUILTIN_ENVIRONMENTS,
235
+ EnvironmentProfileSchema,
236
+ CredentialSchema,
237
+ ENV_NAME_RE,
238
+ loadEnvironment,
239
+ environmentHash,
240
+ toSandboxProfile,
241
+ expandWriteRoots,
242
+ };
@@ -2,8 +2,13 @@
2
2
  // @ts-check
3
3
 
4
4
  /**
5
- * jobSandboxPolicy.cjs — turns a headless PRD job's persona and paths into the
6
- * claude CLI flags that confine it.
5
+ * jobSandboxPolicy.cjs — turns a headless PRD job's resolved environment
6
+ * profile (environmentProfiles.cjs) and paths into the claude CLI flags that
7
+ * confine it, or refuses it. Enforcement (schedulerConfig.environmentEnforcement,
8
+ * default 'enforce'): an environment that requires the OS sandbox when its
9
+ * dependencies are missing is REFUSED (level 'refused', refusal
10
+ * environment_unavailable) — never downgraded to tool rules. The opt-out
11
+ * 'report' mode keeps the old downgrade and records a would-block entry.
7
12
  *
8
13
  * Two levels:
9
14
  * - 'tool-rules' (every persona): keeps --dangerously-skip-permissions but
@@ -12,11 +17,11 @@
12
17
  * bypass flag for the Read/Write tools and plain Bash cat/redirect, but
13
18
  * `python3 -c open(...)` or `sh -c 'cat $1'` still read the file — tool
14
19
  * rules are not containment.
15
- * - 'os-sandbox' (validator, dev-lead, when bwrap+socat / sandbox-exec are
16
- * present): drops the bypass flag, runs under a --permission-mode, and turns
20
+ * - 'os-sandbox' (an environment with osSandboxRequired — validator and
21
+ * dev-lead by default — when bwrap+socat / sandbox-exec are present): drops the bypass flag, runs under a --permission-mode, and turns
17
22
  * on the CLI's OS sandbox (Bash only — in-process tools stay governed by the
18
23
  * permission rules): writes only in the worktree plus declared roots, secret
19
- * files unreadable, Bash network limited to the profile's allowlist.
24
+ * files unreadable, Bash network limited to the environment's allowlist.
20
25
  *
21
26
  * Rule paths: a leading `//` is absolute; a single `/` is relative to the
22
27
  * settings file — so every rule here is `//` + the absolute path sans its `/`.
@@ -26,6 +31,7 @@
26
31
  */
27
32
 
28
33
  const path = require('node:path');
34
+ const { VAULT_FILE_ROOTS, credentialFilePaths } = require('./vaultRefs.cjs');
29
35
 
30
36
  /** Home-relative paths whose contents no job tool may read or write. */
31
37
  const SANDBOX_SECRET_PATHS = Object.freeze([
@@ -33,25 +39,113 @@ const SANDBOX_SECRET_PATHS = Object.freeze([
33
39
  '.netrc',
34
40
  '.ssh',
35
41
  '.gnupg',
36
- 'Self/secrets',
37
42
  '.claude/.credentials.json',
38
43
  '.config/gh',
39
44
  '.google_workspace_mcp',
40
45
  '.config/google-workspace-mcp',
41
46
  '.aws',
42
47
  '.docker/config.json',
48
+ // Every file: vault root (vaultRefs.cjs) — vault values reach only out-of-job servers.
49
+ ...VAULT_FILE_ROOTS,
43
50
  ]);
44
51
 
45
52
  /**
46
- * @typedef {{ readonly permissionMode: string, readonly network: readonly string[] }} SandboxProfile
53
+ * Personas that get an environment profile without declaring one in their
54
+ * frontmatter — the two personas the retired persona-keyed SANDBOX_PROFILES
55
+ * covered, mapped onto the built-in environments that reproduce them
56
+ * (environmentProfiles.cjs). Any other persona gets an environment only by
57
+ * declaring `environment:`; without one it stays on tool rules.
47
58
  */
59
+ const LEGACY_PERSONA_ENVIRONMENTS = Object.freeze({
60
+ validator: 'validator-readonly',
61
+ 'dev-lead': 'headless-default',
62
+ });
63
+
64
+ /** Environment enforcement modes (schedulerConfig.environmentEnforcement). */
65
+ const ENFORCEMENT_MODES = Object.freeze(['report', 'enforce']);
48
66
 
49
- /** @type {Readonly<Record<string, SandboxProfile>>} */
50
- const SANDBOX_PROFILES = Object.freeze({
51
- validator: Object.freeze({ permissionMode: 'default', network: Object.freeze([]) }),
52
- 'dev-lead': Object.freeze({ permissionMode: 'acceptEdits', network: Object.freeze(['registry.npmjs.org']) }),
67
+ /**
68
+ * OS packages that provide each sandbox dependency, per platform — what the
69
+ * readiness banner tells the human to install.
70
+ * @type {Readonly<Record<string, Readonly<Record<string, string>>>>}
71
+ */
72
+ const SANDBOX_DEP_PACKAGES = Object.freeze({
73
+ linux: Object.freeze({ bwrap: 'bubblewrap', socat: 'socat' }),
74
+ darwin: Object.freeze({ 'sandbox-exec': 'sandbox-exec (ships with macOS)' }),
53
75
  });
54
76
 
77
+ /**
78
+ * The install hint for missing sandbox dependencies: the package names, and
79
+ * on linux an apt line. Pure.
80
+ * @param {{ platform: string, missing: string[] }} args
81
+ * @returns {{ packages: string[], command: string|null }}
82
+ */
83
+ function sandboxInstallHint({ platform, missing }) {
84
+ const map = Object.prototype.hasOwnProperty.call(SANDBOX_DEP_PACKAGES, platform) ? SANDBOX_DEP_PACKAGES[platform] : null;
85
+ const bins = (missing || []).filter((m) => map && Object.prototype.hasOwnProperty.call(map, m));
86
+ const packages = [...new Set(bins.map((b) => /** @type {Record<string, string>} */ (map)[b]))];
87
+ const command = platform === 'linux' && packages.length ? `sudo apt install ${packages.join(' ')}` : null;
88
+ return { packages, command };
89
+ }
90
+
91
+ /**
92
+ * @param {unknown} mode
93
+ * @returns {'report'|'enforce'}
94
+ */
95
+ function normalizeMode(mode) {
96
+ return mode === 'report' ? 'report' : 'enforce';
97
+ }
98
+
99
+ /**
100
+ * The environment name a job runs under: the persona's declared
101
+ * `environment:` wins; else the legacy persona default; else null.
102
+ * @param {{ agentType?: string|null, declared?: string|null }} args
103
+ * @returns {string|null}
104
+ */
105
+ function jobEnvironmentName({ agentType, declared } = {}) {
106
+ if (typeof declared === 'string' && declared.trim()) return declared.trim();
107
+ if (typeof agentType === 'string' && Object.prototype.hasOwnProperty.call(LEGACY_PERSONA_ENVIRONMENTS, agentType)) {
108
+ return LEGACY_PERSONA_ENVIRONMENTS[agentType];
109
+ }
110
+ return null;
111
+ }
112
+
113
+ const ROOT_TOKEN_RE = /^\{(worktree|projectRoot|home|tmp)\}(\/.*)?$/;
114
+
115
+ /**
116
+ * @typedef {{ mode: 'none' } | { mode: 'allowlist', hosts: string[] } | { mode: 'open' }} EnvironmentNetwork
117
+ * @typedef {{
118
+ * osSandboxRequired: boolean,
119
+ * permissionMode: string,
120
+ * writeRoots: string[],
121
+ * network: EnvironmentNetwork,
122
+ * secretDenyPaths: string[],
123
+ * webFetch: boolean,
124
+ * webSearch: boolean,
125
+ * }} EnvironmentProfile
126
+ * @typedef {{ id: string, profile: EnvironmentProfile }} ResolvedEnvironment
127
+ */
128
+
129
+ /**
130
+ * @param {string[]} roots
131
+ * @param {{ worktreeDir: string, projectRoot: string, homeDir: string, tmpDir: string }} dirs
132
+ * @returns {string[]}
133
+ */
134
+ function expandRoots(roots, { worktreeDir, projectRoot, homeDir, tmpDir }) {
135
+ /** @type {Record<string, string>} */
136
+ const base = { worktree: worktreeDir, projectRoot, home: homeDir, tmp: tmpDir };
137
+ return roots.map((r) => {
138
+ const m = r.match(ROOT_TOKEN_RE);
139
+ return m ? path.join(base[m[1]], m[2] || '') : r;
140
+ });
141
+ }
142
+
143
+ /** @param {EnvironmentNetwork} n @returns {string[]|null} */
144
+ function networkHosts(n) {
145
+ if (!n || n.mode === 'open') return null;
146
+ return n.mode === 'allowlist' ? [...n.hosts] : [];
147
+ }
148
+
55
149
  /** @type {Readonly<Record<string, readonly string[]>>} */
56
150
  const PLATFORM_DEPS = Object.freeze({
57
151
  linux: Object.freeze(['bwrap', 'socat']),
@@ -89,22 +183,36 @@ function requireAbs(args, field) {
89
183
  }
90
184
 
91
185
  /**
186
+ * @typedef {{ what: 'os_sandbox_unavailable', detail: string }} WouldBlock
187
+ * @typedef {{ code: 'environment_unavailable', detail: string, missing: string[] }} EnvironmentRefusal
92
188
  * @typedef {{
93
- * level: 'os-sandbox'|'tool-rules',
189
+ * level: 'os-sandbox'|'tool-rules'|'refused',
94
190
  * argv: string[],
95
191
  * settings: Record<string, unknown>,
96
- * summary: { level: 'os-sandbox'|'tool-rules', profile: string|null, network: string[]|null, reason: string|null },
192
+ * summary: { level: 'os-sandbox'|'tool-rules'|'refused', profile: string|null, environment: string|null, network: string[]|null, reason: string|null },
193
+ * wouldBlock: WouldBlock[],
194
+ * refusal: EnvironmentRefusal|null,
97
195
  * }} JobSandboxResult
98
196
  */
99
197
 
100
198
  /**
199
+ * Sandbox flags for one job, derived from its resolved environment profile.
200
+ * `environment` null → tool rules (no profile applies to this job). A profile
201
+ * with osSandboxRequired false → tool rules. A profile that requires the OS
202
+ * sandbox when deps are missing → in 'enforce' mode (the default) level
203
+ * 'refused' with `refusal` { code: 'environment_unavailable', detail: the
204
+ * missing deps } and no argv — the caller parks the job, never spawns it; in
205
+ * 'report' mode tool rules plus a `wouldBlock` entry.
206
+ *
101
207
  * @param {{
102
208
  * agentType?: string|null,
209
+ * environment?: ResolvedEnvironment|null,
103
210
  * worktreeDir: string,
104
211
  * projectRoot: string,
105
212
  * homeDir: string,
106
213
  * tmpDir: string,
107
214
  * deps?: { available: boolean, missing?: string[] }|null,
215
+ * mode?: 'report'|'enforce'|string|null,
108
216
  * }} args
109
217
  * @returns {JobSandboxResult}
110
218
  */
@@ -116,20 +224,40 @@ function buildJobSandboxSettings(args) {
116
224
  const tmpDir = requireAbs(raw, 'tmpDir');
117
225
  const agentType = typeof args.agentType === 'string' && args.agentType ? args.agentType : null;
118
226
  const deps = args.deps;
227
+ const mode = normalizeMode(args.mode);
228
+ const env = args.environment && args.environment.profile ? args.environment : null;
229
+ const envId = env ? String(env.id) : null;
230
+ const profile = env ? env.profile : null;
119
231
 
120
- const secretAbs = SANDBOX_SECRET_PATHS.map((p) => path.join(homeDir, p));
232
+ const baseRel = profile && Array.isArray(profile.secretDenyPaths) ? profile.secretDenyPaths : SANDBOX_SECRET_PATHS;
233
+ // Each file: credential path is denied whatever the profile lists (the
234
+ // built-ins already deny every VAULT_FILE_ROOTS entry via SANDBOX_SECRET_PATHS).
235
+ const secretRel = [...new Set([...baseRel, ...credentialFilePaths(profile)])];
236
+ const secretAbs = secretRel.map((p) => path.join(homeDir, p));
121
237
  const deny = secretAbs.flatMap(denyRulesFor);
122
238
 
123
- const profile =
124
- agentType && Object.prototype.hasOwnProperty.call(SANDBOX_PROFILES, agentType) ? SANDBOX_PROFILES[agentType] : null;
125
-
239
+ /** @type {WouldBlock[]} */
240
+ const wouldBlock = [];
126
241
  /** @type {string|null} */
127
242
  let reason = null;
128
243
  if (!profile) {
129
- reason = `no sandbox profile for persona ${agentType ?? '(none)'}`;
244
+ reason = `no environment profile for persona ${agentType ?? '(none)'}`;
245
+ } else if (!profile.osSandboxRequired) {
246
+ reason = `environment ${envId} does not require the OS sandbox`;
130
247
  } else if (!deps || deps.available !== true) {
131
248
  const missing = deps && Array.isArray(deps.missing) && deps.missing.length ? deps.missing : ['unknown'];
132
249
  reason = `OS sandbox unavailable, missing: ${missing.join(', ')}`;
250
+ if (mode === 'enforce') {
251
+ return {
252
+ level: 'refused',
253
+ argv: [],
254
+ settings: {},
255
+ summary: { level: 'refused', profile: agentType, environment: envId, network: null, reason },
256
+ wouldBlock: [],
257
+ refusal: { code: 'environment_unavailable', detail: missing.join(', '), missing: [...missing] },
258
+ };
259
+ }
260
+ wouldBlock.push({ what: 'os_sandbox_unavailable', detail: reason });
133
261
  }
134
262
 
135
263
  if (!profile || reason) {
@@ -138,14 +266,18 @@ function buildJobSandboxSettings(args) {
138
266
  level: 'tool-rules',
139
267
  argv: ['--dangerously-skip-permissions', '--settings', JSON.stringify(settings)],
140
268
  settings,
141
- summary: { level: 'tool-rules', profile: agentType, network: null, reason },
269
+ summary: { level: 'tool-rules', profile: agentType, environment: envId, network: null, reason },
270
+ wouldBlock,
271
+ refusal: null,
142
272
  };
143
273
  }
144
274
 
275
+ const hosts = networkHosts(profile.network);
276
+ const denyTools = [...(profile.webFetch ? [] : ['WebFetch']), ...(profile.webSearch ? [] : ['WebSearch'])];
145
277
  const settings = {
146
278
  permissions: {
147
279
  allow: ['Read(//**)', 'Glob', 'Grep', 'Bash', 'Skill', 'Agent', 'ToolSearch', 'TodoWrite'],
148
- deny: [...deny, 'WebFetch', 'WebSearch'],
280
+ deny: [...deny, ...denyTools],
149
281
  },
150
282
  sandbox: {
151
283
  enabled: true,
@@ -155,27 +287,96 @@ function buildJobSandboxSettings(args) {
155
287
  filesystem: {
156
288
  // .git: a job worktree commits into the main checkout's .git (objects,
157
289
  // refs, worktrees/<name>); the CLI sandbox keeps .git/hooks and
158
- // .git/config read-only itself.
159
- allowWrite: [
160
- worktreeDir,
161
- path.join(projectRoot, '.git'),
162
- tmpDir,
163
- path.join(homeDir, '.npm'),
164
- path.join(homeDir, '.cache'),
165
- path.join(projectRoot, 'node_modules', '.vite'),
166
- path.join(projectRoot, 'node_modules', '.vitest'),
167
- ],
290
+ // .git/config read-only itself. The roots come from the profile.
291
+ allowWrite: expandRoots(profile.writeRoots, { worktreeDir, projectRoot, homeDir, tmpDir }),
168
292
  denyRead: secretAbs,
169
293
  },
170
294
  credentials: { files: secretAbs.map((p) => ({ path: p, mode: 'deny' })) },
171
- network: { allowedDomains: [...profile.network], strictAllowlist: true },
295
+ // 'open' network: no allow-list at all.
296
+ ...(hosts ? { network: { allowedDomains: hosts, strictAllowlist: true } } : {}),
172
297
  },
173
298
  };
174
299
  return {
175
300
  level: 'os-sandbox',
176
301
  argv: ['--permission-mode', profile.permissionMode, '--settings', JSON.stringify(settings)],
177
302
  settings,
178
- summary: { level: 'os-sandbox', profile: agentType, network: [...profile.network], reason: null },
303
+ summary: { level: 'os-sandbox', profile: agentType, environment: envId, network: hosts ? [...hosts] : null, reason: null },
304
+ wouldBlock,
305
+ refusal: null,
306
+ };
307
+ }
308
+
309
+ /**
310
+ * The env vars the job's PreToolUse hook (guard-tool-risk) reads to deny
311
+ * ('enforce', the default) or only report ('report') the WebFetch/WebSearch
312
+ * calls the job's environment disallows. Empty when no environment applies.
313
+ * @param {{ environment?: ResolvedEnvironment|null, mode: string, agentType?: string|null }} args
314
+ * @returns {Record<string, string>}
315
+ */
316
+ function environmentHookEnv({ environment, mode, agentType }) {
317
+ if (!environment || !environment.profile) return {};
318
+ const p = environment.profile;
319
+ return {
320
+ SM_JOB_ENVIRONMENT: JSON.stringify({ id: environment.id, webFetch: !!p.webFetch, webSearch: !!p.webSearch, network: p.network }),
321
+ SM_JOB_ENVIRONMENT_MODE: normalizeMode(mode),
322
+ SM_JOB_PERSONA: agentType || '',
323
+ };
324
+ }
325
+
326
+ /** @param {unknown} url @returns {string|null} */
327
+ function hostOf(url) {
328
+ if (typeof url !== 'string' || !url) return null;
329
+ try { return new URL(url).hostname.toLowerCase() || null; } catch { return null; }
330
+ }
331
+
332
+ /** @param {string} host @param {string} pattern */
333
+ function hostMatches(host, pattern) {
334
+ const p = String(pattern).toLowerCase();
335
+ if (p.startsWith('*.')) return host.endsWith(p.slice(1)) || host === p.slice(2);
336
+ return host === p;
337
+ }
338
+
339
+ /**
340
+ * What a job's environment would block about one WebFetch/WebSearch call,
341
+ * or null. Pure.
342
+ * - 'webfetch_not_allowed' / 'websearch_not_allowed': the profile disallows the tool.
343
+ * - 'host_off_allowlist': WebFetch allowed, but the URL's host is outside an
344
+ * allow-list network (or the network is 'none').
345
+ * @param {{ webFetch?: boolean, webSearch?: boolean, network?: EnvironmentNetwork }|null} env
346
+ * @param {string} toolName
347
+ * @param {any} input
348
+ * @returns {{ what: string, detail: string }|null}
349
+ */
350
+ function webToolWouldBlock(env, toolName, input) {
351
+ if (!env || typeof env !== 'object') return null;
352
+ if (toolName === 'WebSearch') {
353
+ if (env.webSearch) return null;
354
+ const q = input && typeof input.query === 'string' ? input.query.slice(0, 200) : '';
355
+ return { what: 'websearch_not_allowed', detail: q };
356
+ }
357
+ if (toolName !== 'WebFetch') return null;
358
+ const url = input && typeof input.url === 'string' ? input.url.slice(0, 500) : '';
359
+ if (!env.webFetch) return { what: 'webfetch_not_allowed', detail: url };
360
+ const n = env.network;
361
+ if (!n || n.mode === 'open') return null;
362
+ const host = hostOf(url);
363
+ const hosts = n.mode === 'allowlist' ? n.hosts : [];
364
+ if (host && hosts.some((h) => hostMatches(host, h))) return null;
365
+ return { what: 'host_off_allowlist', detail: host || url };
366
+ }
367
+
368
+ /**
369
+ * One 'environment_would_block' audit record's fields.
370
+ * @param {{ slug?: string|null, persona?: string|null, environment?: string|null, what: string, detail?: string|null, mode?: string|null }} f
371
+ */
372
+ function wouldBlockRecord({ slug, persona, environment, what, detail, mode }) {
373
+ return {
374
+ slug: slug || null,
375
+ persona: persona || null,
376
+ environment: environment || null,
377
+ what,
378
+ detail: detail ?? null,
379
+ mode: normalizeMode(mode),
179
380
  };
180
381
  }
181
382
 
@@ -195,8 +396,15 @@ function sandboxChildEnv(policy, tmpDir) {
195
396
 
196
397
  module.exports = {
197
398
  SANDBOX_SECRET_PATHS,
198
- SANDBOX_PROFILES,
399
+ LEGACY_PERSONA_ENVIRONMENTS,
400
+ ENFORCEMENT_MODES,
401
+ SANDBOX_DEP_PACKAGES,
402
+ sandboxInstallHint,
403
+ jobEnvironmentName,
199
404
  sandboxDependencies,
200
405
  buildJobSandboxSettings,
201
406
  sandboxChildEnv,
407
+ environmentHookEnv,
408
+ webToolWouldBlock,
409
+ wouldBlockRecord,
202
410
  };