devworkspace 0.5.1 → 0.5.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 (380) hide show
  1. package/CHANGELOG.md +30 -2
  2. package/README.md +57 -509
  3. package/dist/agents/claude/adapter.js +0 -1
  4. package/dist/agents/claude/content.js +0 -1
  5. package/dist/agents/codex/adapter.js +0 -1
  6. package/dist/agents/copilot/adapter.js +0 -1
  7. package/dist/agents/cursor/adapter.js +0 -1
  8. package/dist/agents/index.js +0 -1
  9. package/dist/agents/shared.js +0 -1
  10. package/dist/agents/types.js +0 -1
  11. package/dist/cli/args.d.ts +16 -0
  12. package/dist/cli/args.js +5 -1
  13. package/dist/cli/help.js +59 -17
  14. package/dist/cli/main.js +0 -1
  15. package/dist/cli/prompt.d.ts +15 -0
  16. package/dist/cli/prompt.js +113 -0
  17. package/dist/cli/render.d.ts +10 -0
  18. package/dist/cli/render.js +174 -4
  19. package/dist/cli/run.d.ts +3 -0
  20. package/dist/cli/run.js +366 -17
  21. package/dist/config/feature-gate.d.ts +15 -0
  22. package/dist/config/feature-gate.js +77 -0
  23. package/dist/config/feature-registry.d.ts +49 -0
  24. package/dist/config/feature-registry.js +451 -0
  25. package/dist/config/schemas.js +0 -1
  26. package/dist/config/settings.d.ts +54 -0
  27. package/dist/config/settings.js +293 -0
  28. package/dist/config/validate.js +0 -1
  29. package/dist/core/artifacts.js +0 -1
  30. package/dist/core/contracts.js +0 -1
  31. package/dist/core/migrations.js +0 -1
  32. package/dist/core/version.js +0 -1
  33. package/dist/core/versioned.js +0 -1
  34. package/dist/core/workspace.d.ts +1 -0
  35. package/dist/core/workspace.js +1 -1
  36. package/dist/decisions/decision.js +0 -1
  37. package/dist/discovery/cache.js +0 -1
  38. package/dist/discovery/commands.js +0 -1
  39. package/dist/discovery/detect.js +0 -1
  40. package/dist/discovery/docs.js +0 -1
  41. package/dist/discovery/entrypoints.js +0 -1
  42. package/dist/discovery/ignore.js +0 -1
  43. package/dist/discovery/scan.js +0 -1
  44. package/dist/discovery/types.js +0 -1
  45. package/dist/dx/dashboard.js +2 -1
  46. package/dist/dx/guidance.js +0 -1
  47. package/dist/dx/guided-setup.d.ts +102 -0
  48. package/dist/dx/guided-setup.js +508 -0
  49. package/dist/dx/index.js +0 -1
  50. package/dist/dx/onboarding.js +0 -1
  51. package/dist/dx/types.js +0 -1
  52. package/dist/errors/index.js +0 -1
  53. package/dist/features/schema.js +0 -1
  54. package/dist/features/types.js +0 -1
  55. package/dist/features/validate.js +0 -1
  56. package/dist/git/git.js +0 -1
  57. package/dist/index.d.ts +15 -5
  58. package/dist/index.js +10 -2
  59. package/dist/integrations/adapters/agent-skills.js +0 -1
  60. package/dist/integrations/adapters/claudePlugin.js +0 -1
  61. package/dist/integrations/adapters/graphify.js +0 -1
  62. package/dist/integrations/adapters/omniroute.js +0 -1
  63. package/dist/integrations/adapters/pluginSkill.js +0 -1
  64. package/dist/integrations/adapters/ponytail.js +0 -1
  65. package/dist/integrations/exec.js +0 -1
  66. package/dist/integrations/index.js +0 -1
  67. package/dist/integrations/manager.d.ts +2 -1
  68. package/dist/integrations/manager.js +22 -3
  69. package/dist/integrations/notices.js +0 -1
  70. package/dist/integrations/persistentPath.js +0 -1
  71. package/dist/integrations/protect.js +0 -1
  72. package/dist/integrations/state.js +0 -1
  73. package/dist/integrations/types.d.ts +1 -1
  74. package/dist/integrations/types.js +1 -1
  75. package/dist/intelligence/agents/profiles.js +0 -1
  76. package/dist/intelligence/agents/registry.js +0 -1
  77. package/dist/intelligence/agents/types.js +0 -1
  78. package/dist/intelligence/observability/tracer.js +0 -1
  79. package/dist/intelligence/observability/types.js +0 -1
  80. package/dist/intelligence/orchestration/engine.d.ts +13 -4
  81. package/dist/intelligence/orchestration/engine.js +332 -54
  82. package/dist/intelligence/orchestration/lock-manager.js +0 -1
  83. package/dist/intelligence/orchestration/store.js +0 -1
  84. package/dist/intelligence/orchestration/types.d.ts +28 -1
  85. package/dist/intelligence/orchestration/types.js +0 -1
  86. package/dist/intelligence/routing/matcher.js +0 -1
  87. package/dist/intelligence/routing/router.js +0 -1
  88. package/dist/intelligence/routing/types.js +0 -1
  89. package/dist/intelligence/runtime/adk/adapter.js +1 -2
  90. package/dist/intelligence/runtime/adk/detector.js +0 -1
  91. package/dist/intelligence/runtime/auth-provider.d.ts +63 -0
  92. package/dist/intelligence/runtime/auth-provider.js +201 -0
  93. package/dist/intelligence/runtime/boundary.d.ts +118 -6
  94. package/dist/intelligence/runtime/boundary.js +720 -38
  95. package/dist/intelligence/runtime/changes.d.ts +59 -0
  96. package/dist/intelligence/runtime/changes.js +362 -0
  97. package/dist/intelligence/runtime/external.d.ts +1 -0
  98. package/dist/intelligence/runtime/external.js +9 -6
  99. package/dist/intelligence/runtime/native.js +0 -1
  100. package/dist/intelligence/runtime/types.d.ts +64 -2
  101. package/dist/intelligence/runtime/types.js +0 -1
  102. package/dist/intelligence/security/audit.js +8 -2
  103. package/dist/intelligence/security/policy.js +0 -1
  104. package/dist/intelligence/security/types.d.ts +8 -0
  105. package/dist/intelligence/security/types.js +0 -1
  106. package/dist/intelligence/skills/builtins.js +0 -1
  107. package/dist/intelligence/skills/loader.js +0 -1
  108. package/dist/intelligence/skills/registry.js +0 -1
  109. package/dist/intelligence/skills/types.js +0 -1
  110. package/dist/intelligence/verification/engine.d.ts +10 -2
  111. package/dist/intelligence/verification/engine.js +53 -9
  112. package/dist/intelligence/verification/reviewer.d.ts +18 -2
  113. package/dist/intelligence/verification/reviewer.js +356 -4
  114. package/dist/intelligence/verification/types.d.ts +60 -0
  115. package/dist/intelligence/verification/types.js +0 -1
  116. package/dist/knowledge/facts.js +0 -1
  117. package/dist/mcp/protocol.js +0 -1
  118. package/dist/mcp/server.js +38 -2
  119. package/dist/mcp/setup.js +5 -2
  120. package/dist/mcp/tools.js +0 -1
  121. package/dist/mcp/types.js +0 -1
  122. package/dist/mcp/verify.js +0 -1
  123. package/dist/portability/bundle.js +0 -1
  124. package/dist/prompts/onboarding.js +0 -1
  125. package/dist/prompts/refresh.js +0 -1
  126. package/dist/prompts/requirements.js +0 -1
  127. package/dist/security/files.js +0 -1
  128. package/dist/security/redact.js +0 -1
  129. package/dist/services/agent.js +2 -1
  130. package/dist/services/analysis.js +0 -1
  131. package/dist/services/common.js +0 -1
  132. package/dist/services/doctor.js +13 -2
  133. package/dist/services/drift.js +0 -1
  134. package/dist/services/features.js +5 -1
  135. package/dist/services/graph.js +4 -1
  136. package/dist/services/init.js +0 -1
  137. package/dist/services/integrations.d.ts +2 -1
  138. package/dist/services/integrations.js +29 -6
  139. package/dist/services/intelligence.d.ts +2 -2
  140. package/dist/services/intelligence.js +38 -36
  141. package/dist/services/knowledge.js +0 -1
  142. package/dist/services/migrate.js +0 -1
  143. package/dist/services/modules.d.ts +85 -0
  144. package/dist/services/modules.js +313 -0
  145. package/dist/services/portability.js +0 -1
  146. package/dist/services/records.js +5 -1
  147. package/dist/services/refresh.js +0 -1
  148. package/dist/services/reset.js +0 -1
  149. package/dist/services/settings.d.ts +36 -0
  150. package/dist/services/settings.js +102 -0
  151. package/dist/services/setup.d.ts +4 -5
  152. package/dist/services/setup.js +40 -28
  153. package/dist/services/standards.js +10 -1
  154. package/dist/services/status.js +0 -1
  155. package/dist/services/taskContext.js +0 -1
  156. package/dist/services/tasks.js +9 -1
  157. package/dist/services/verify.js +7 -2
  158. package/dist/sessions/session.js +0 -1
  159. package/dist/standards/acquisition/ingest.js +0 -1
  160. package/dist/standards/applicability/engine.js +0 -1
  161. package/dist/standards/builtin/code-quality.js +0 -1
  162. package/dist/standards/builtin/database-safety.js +0 -1
  163. package/dist/standards/builtin/index.js +0 -1
  164. package/dist/standards/builtin/security-baseline.js +0 -1
  165. package/dist/standards/builtin/testing-contracts.js +0 -1
  166. package/dist/standards/builtin/undo-kit.js +0 -1
  167. package/dist/standards/config/config.js +0 -1
  168. package/dist/standards/distribution/cache.js +0 -1
  169. package/dist/standards/distribution/index.js +0 -1
  170. package/dist/standards/distribution/keys.js +0 -1
  171. package/dist/standards/distribution/package.js +0 -1
  172. package/dist/standards/distribution/server.js +0 -1
  173. package/dist/standards/distribution/sync.js +0 -1
  174. package/dist/standards/distribution/types.js +0 -1
  175. package/dist/standards/engine/compliance.js +0 -1
  176. package/dist/standards/engine/engine.js +0 -1
  177. package/dist/standards/engine/reporter.js +0 -1
  178. package/dist/standards/index.js +0 -1
  179. package/dist/standards/registry/registry.js +0 -1
  180. package/dist/standards/schema/types.js +0 -1
  181. package/dist/standards/schema/validate.js +0 -1
  182. package/dist/standards/templates/index.js +0 -1
  183. package/dist/standards/validators/database.js +0 -1
  184. package/dist/standards/validators/quality.js +0 -1
  185. package/dist/standards/validators/registry.js +0 -1
  186. package/dist/standards/validators/security.js +0 -1
  187. package/dist/standards/validators/testing.js +0 -1
  188. package/dist/standards/validators/types.js +0 -1
  189. package/dist/standards/validators/undo-kit.js +0 -1
  190. package/dist/tasks/routing.js +0 -1
  191. package/dist/tasks/task.js +0 -1
  192. package/dist/utils/cleanup.js +0 -1
  193. package/dist/utils/fs.js +0 -1
  194. package/dist/utils/lock.js +92 -49
  195. package/dist/utils/logger.js +0 -1
  196. package/dist/utils/paths.js +0 -1
  197. package/dist/utils/proc.d.ts +8 -0
  198. package/dist/utils/proc.js +54 -46
  199. package/dist/verification/safety.js +0 -1
  200. package/dist/verification/scope.js +0 -1
  201. package/docs/architecture/global-standards-architecture.md +287 -0
  202. package/docs/archive/global-standards/GLOBAL_STANDARDS_AUDIT.md +99 -0
  203. package/docs/archive/global-standards/GLOBAL_STANDARDS_FINAL_STATUS.md +138 -0
  204. package/docs/archive/global-standards/GLOBAL_STANDARDS_IMPLEMENTATION_PLAN.md +100 -0
  205. package/docs/archive/global-standards/GLOBAL_STANDARDS_INDEPENDENT_AUDIT.md +219 -0
  206. package/docs/archive/global-standards/GLOBAL_STANDARDS_SECURITY_REPORT.md +184 -0
  207. package/docs/configuration.md +67 -0
  208. package/docs/contributing.md +15 -4
  209. package/docs/development/EXECUTION_STATE.md +50 -0
  210. package/docs/features.md +80 -0
  211. package/docs/getting-started.md +69 -111
  212. package/docs/guides/global-standards-migration.md +100 -0
  213. package/docs/integrations.md +7 -0
  214. package/docs/security/THIRD_PARTY_LICENSES.md +41 -0
  215. package/docs/testing/FINAL_CORRECTION_AND_CLEANUP_REPORT.md +92 -0
  216. package/docs/testing/global-standards-real-project-tests.md +218 -0
  217. package/docs/testing/global-standards-test-report.md +89 -0
  218. package/docs/testing/global-standards-verification-matrix.md +174 -0
  219. package/docs/troubleshooting.md +3 -0
  220. package/package.json +1 -1
  221. package/dist/agents/claude/adapter.js.map +0 -1
  222. package/dist/agents/claude/content.js.map +0 -1
  223. package/dist/agents/codex/adapter.js.map +0 -1
  224. package/dist/agents/copilot/adapter.js.map +0 -1
  225. package/dist/agents/cursor/adapter.js.map +0 -1
  226. package/dist/agents/index.js.map +0 -1
  227. package/dist/agents/shared.js.map +0 -1
  228. package/dist/agents/types.js.map +0 -1
  229. package/dist/cli/args.js.map +0 -1
  230. package/dist/cli/help.js.map +0 -1
  231. package/dist/cli/main.js.map +0 -1
  232. package/dist/cli/render.js.map +0 -1
  233. package/dist/cli/run.js.map +0 -1
  234. package/dist/config/schemas.js.map +0 -1
  235. package/dist/config/validate.js.map +0 -1
  236. package/dist/core/artifacts.js.map +0 -1
  237. package/dist/core/contracts.js.map +0 -1
  238. package/dist/core/migrations.js.map +0 -1
  239. package/dist/core/version.js.map +0 -1
  240. package/dist/core/versioned.js.map +0 -1
  241. package/dist/core/workspace.js.map +0 -1
  242. package/dist/decisions/decision.js.map +0 -1
  243. package/dist/discovery/cache.js.map +0 -1
  244. package/dist/discovery/commands.js.map +0 -1
  245. package/dist/discovery/detect.js.map +0 -1
  246. package/dist/discovery/docs.js.map +0 -1
  247. package/dist/discovery/entrypoints.js.map +0 -1
  248. package/dist/discovery/ignore.js.map +0 -1
  249. package/dist/discovery/scan.js.map +0 -1
  250. package/dist/discovery/types.js.map +0 -1
  251. package/dist/dx/dashboard.js.map +0 -1
  252. package/dist/dx/guidance.js.map +0 -1
  253. package/dist/dx/index.js.map +0 -1
  254. package/dist/dx/onboarding.js.map +0 -1
  255. package/dist/dx/types.js.map +0 -1
  256. package/dist/errors/index.js.map +0 -1
  257. package/dist/features/schema.js.map +0 -1
  258. package/dist/features/types.js.map +0 -1
  259. package/dist/features/validate.js.map +0 -1
  260. package/dist/git/git.js.map +0 -1
  261. package/dist/index.js.map +0 -1
  262. package/dist/integrations/adapters/agent-skills.js.map +0 -1
  263. package/dist/integrations/adapters/claudePlugin.js.map +0 -1
  264. package/dist/integrations/adapters/graphify.js.map +0 -1
  265. package/dist/integrations/adapters/omniroute.js.map +0 -1
  266. package/dist/integrations/adapters/pluginSkill.js.map +0 -1
  267. package/dist/integrations/adapters/ponytail.js.map +0 -1
  268. package/dist/integrations/exec.js.map +0 -1
  269. package/dist/integrations/index.js.map +0 -1
  270. package/dist/integrations/manager.js.map +0 -1
  271. package/dist/integrations/notices.js.map +0 -1
  272. package/dist/integrations/persistentPath.js.map +0 -1
  273. package/dist/integrations/protect.js.map +0 -1
  274. package/dist/integrations/state.js.map +0 -1
  275. package/dist/integrations/types.js.map +0 -1
  276. package/dist/intelligence/agents/profiles.js.map +0 -1
  277. package/dist/intelligence/agents/registry.js.map +0 -1
  278. package/dist/intelligence/agents/types.js.map +0 -1
  279. package/dist/intelligence/observability/tracer.js.map +0 -1
  280. package/dist/intelligence/observability/types.js.map +0 -1
  281. package/dist/intelligence/orchestration/engine.js.map +0 -1
  282. package/dist/intelligence/orchestration/lock-manager.js.map +0 -1
  283. package/dist/intelligence/orchestration/store.js.map +0 -1
  284. package/dist/intelligence/orchestration/types.js.map +0 -1
  285. package/dist/intelligence/routing/matcher.js.map +0 -1
  286. package/dist/intelligence/routing/router.js.map +0 -1
  287. package/dist/intelligence/routing/types.js.map +0 -1
  288. package/dist/intelligence/runtime/adk/adapter.js.map +0 -1
  289. package/dist/intelligence/runtime/adk/detector.js.map +0 -1
  290. package/dist/intelligence/runtime/boundary.js.map +0 -1
  291. package/dist/intelligence/runtime/external.js.map +0 -1
  292. package/dist/intelligence/runtime/native.js.map +0 -1
  293. package/dist/intelligence/runtime/types.js.map +0 -1
  294. package/dist/intelligence/security/audit.js.map +0 -1
  295. package/dist/intelligence/security/policy.js.map +0 -1
  296. package/dist/intelligence/security/types.js.map +0 -1
  297. package/dist/intelligence/skills/builtins.js.map +0 -1
  298. package/dist/intelligence/skills/loader.js.map +0 -1
  299. package/dist/intelligence/skills/registry.js.map +0 -1
  300. package/dist/intelligence/skills/types.js.map +0 -1
  301. package/dist/intelligence/verification/engine.js.map +0 -1
  302. package/dist/intelligence/verification/reviewer.js.map +0 -1
  303. package/dist/intelligence/verification/types.js.map +0 -1
  304. package/dist/knowledge/facts.js.map +0 -1
  305. package/dist/mcp/protocol.js.map +0 -1
  306. package/dist/mcp/server.js.map +0 -1
  307. package/dist/mcp/setup.js.map +0 -1
  308. package/dist/mcp/tools.js.map +0 -1
  309. package/dist/mcp/types.js.map +0 -1
  310. package/dist/mcp/verify.js.map +0 -1
  311. package/dist/portability/bundle.js.map +0 -1
  312. package/dist/prompts/onboarding.js.map +0 -1
  313. package/dist/prompts/refresh.js.map +0 -1
  314. package/dist/prompts/requirements.js.map +0 -1
  315. package/dist/security/files.js.map +0 -1
  316. package/dist/security/redact.js.map +0 -1
  317. package/dist/services/agent.js.map +0 -1
  318. package/dist/services/analysis.js.map +0 -1
  319. package/dist/services/common.js.map +0 -1
  320. package/dist/services/doctor.js.map +0 -1
  321. package/dist/services/drift.js.map +0 -1
  322. package/dist/services/features.js.map +0 -1
  323. package/dist/services/graph.js.map +0 -1
  324. package/dist/services/init.js.map +0 -1
  325. package/dist/services/integrations.js.map +0 -1
  326. package/dist/services/intelligence.js.map +0 -1
  327. package/dist/services/knowledge.js.map +0 -1
  328. package/dist/services/migrate.js.map +0 -1
  329. package/dist/services/portability.js.map +0 -1
  330. package/dist/services/records.js.map +0 -1
  331. package/dist/services/refresh.js.map +0 -1
  332. package/dist/services/reset.js.map +0 -1
  333. package/dist/services/setup.js.map +0 -1
  334. package/dist/services/standards.js.map +0 -1
  335. package/dist/services/status.js.map +0 -1
  336. package/dist/services/taskContext.js.map +0 -1
  337. package/dist/services/tasks.js.map +0 -1
  338. package/dist/services/verify.js.map +0 -1
  339. package/dist/sessions/session.js.map +0 -1
  340. package/dist/standards/acquisition/ingest.js.map +0 -1
  341. package/dist/standards/applicability/engine.js.map +0 -1
  342. package/dist/standards/builtin/code-quality.js.map +0 -1
  343. package/dist/standards/builtin/database-safety.js.map +0 -1
  344. package/dist/standards/builtin/index.js.map +0 -1
  345. package/dist/standards/builtin/security-baseline.js.map +0 -1
  346. package/dist/standards/builtin/testing-contracts.js.map +0 -1
  347. package/dist/standards/builtin/undo-kit.js.map +0 -1
  348. package/dist/standards/config/config.js.map +0 -1
  349. package/dist/standards/distribution/cache.js.map +0 -1
  350. package/dist/standards/distribution/index.js.map +0 -1
  351. package/dist/standards/distribution/keys.js.map +0 -1
  352. package/dist/standards/distribution/package.js.map +0 -1
  353. package/dist/standards/distribution/server.js.map +0 -1
  354. package/dist/standards/distribution/sync.js.map +0 -1
  355. package/dist/standards/distribution/types.js.map +0 -1
  356. package/dist/standards/engine/compliance.js.map +0 -1
  357. package/dist/standards/engine/engine.js.map +0 -1
  358. package/dist/standards/engine/reporter.js.map +0 -1
  359. package/dist/standards/index.js.map +0 -1
  360. package/dist/standards/registry/registry.js.map +0 -1
  361. package/dist/standards/schema/types.js.map +0 -1
  362. package/dist/standards/schema/validate.js.map +0 -1
  363. package/dist/standards/templates/index.js.map +0 -1
  364. package/dist/standards/validators/database.js.map +0 -1
  365. package/dist/standards/validators/quality.js.map +0 -1
  366. package/dist/standards/validators/registry.js.map +0 -1
  367. package/dist/standards/validators/security.js.map +0 -1
  368. package/dist/standards/validators/testing.js.map +0 -1
  369. package/dist/standards/validators/types.js.map +0 -1
  370. package/dist/standards/validators/undo-kit.js.map +0 -1
  371. package/dist/tasks/routing.js.map +0 -1
  372. package/dist/tasks/task.js.map +0 -1
  373. package/dist/utils/cleanup.js.map +0 -1
  374. package/dist/utils/fs.js.map +0 -1
  375. package/dist/utils/lock.js.map +0 -1
  376. package/dist/utils/logger.js.map +0 -1
  377. package/dist/utils/paths.js.map +0 -1
  378. package/dist/utils/proc.js.map +0 -1
  379. package/dist/verification/safety.js.map +0 -1
  380. package/dist/verification/scope.js.map +0 -1
@@ -1,16 +1,468 @@
1
1
  import crypto from 'node:crypto';
2
2
  import { promises as fs } from 'node:fs';
3
3
  import path from 'node:path';
4
- import { createMinimalExecutionEnv, run } from '../../utils/proc.js';
4
+ import { captureWorkspaceSnapshotDetailed, detectGitRenames, diffWorkspaceSnapshots, } from './changes.js';
5
+ import { createMinimalExecutionEnv, startRun } from '../../utils/proc.js';
5
6
  import { assertNoSymlinkEscape, isInside } from '../../utils/paths.js';
7
+ import { atomicWriteJson } from '../../utils/fs.js';
8
+ import { withLock } from '../../utils/lock.js';
9
+ import { DevWorkspaceError } from '../../errors/index.js';
6
10
  import { redact } from '../../security/redact.js';
7
11
  import { SecurityPolicyEvaluator } from '../security/policy.js';
12
+ import { SecurityAuditLogger } from '../security/audit.js';
8
13
  export const MAX_RUNTIME_OUTPUT_CHARS = 50_000;
9
- const SHELL_BINARIES = new Set(['sh', 'bash', 'zsh', 'dash', 'cmd', 'cmd.exe', 'powershell', 'powershell.exe', 'pwsh', 'pwsh.exe']);
10
- const DESTRUCTIVE_EXEC_RE = /\b(?:rm\s+-[a-zA-Z]*[rf][a-zA-Z]*|mkfs|format\s+[a-zA-Z]:|shutdown|reboot|dd\s+if=|del\s+\/[sq])\b/i;
14
+ export const DEFAULT_GRANT_TTL_MS = 15 * 60_000;
15
+ const VALID_AUTH_METHODS = new Set([
16
+ 'cli-local-user',
17
+ 'ci-oidc',
18
+ 'signed-token',
19
+ 'api-key-verified',
20
+ 'service-account',
21
+ ]);
22
+ const REVOKED_GRANTS_REL = '.devworkspace/orchestration/revoked-grants.json';
23
+ const REVOCATION_AUTH_LOCK_NAME = 'revocation-auth.lock';
24
+ /**
25
+ * Shared mutual-exclusion lock serializing approval grant revocations with final execution authorization
26
+ * and child-process spawn creation so a completed revocation can never race with process start.
27
+ */
28
+ export async function withRevocationAuthLock(workspaceRoot, fn) {
29
+ if (!workspaceRoot || !workspaceRoot.trim()) {
30
+ return fn();
31
+ }
32
+ const dwDir = path.join(path.resolve(workspaceRoot), '.devworkspace');
33
+ return withLock(dwDir, fn, {
34
+ name: REVOCATION_AUTH_LOCK_NAME,
35
+ timeoutMs: 10_000,
36
+ staleMs: 60_000,
37
+ });
38
+ }
39
+ const SHELL_BINARIES = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'csh', 'tcsh', 'fish', 'cmd', 'cmd.exe', 'powershell', 'powershell.exe', 'pwsh', 'pwsh.exe']);
40
+ const INTERPRETER_BASES = new Set(['node', 'python', 'python3', 'py', 'ruby', 'perl', 'php', 'deno', 'bun']);
41
+ const ALLOWED_TOOL_BASES = new Set(['npm', 'npx', 'git', 'tsc', 'vitest', 'jest', 'eslint', 'claude', 'codex', 'cursor']);
42
+ const DESTRUCTIVE_BIN_BASES = new Set(['rm', 'rmdir', 'del', 'erase', 'mkfs', 'format', 'shutdown', 'reboot', 'halt', 'dd', 'dropdb']);
43
+ const DESTRUCTIVE_EXEC_RE = /\b(?:rm\s+-[a-zA-Z]*[rf][a-zA-Z]*|mkfs|format\s+[a-zA-Z]:|shutdown|reboot|dd\s+if=|del\s+\/[sq]|dropdb|prisma\s+migrate\s+reset)\b/i;
44
+ function normalizeExeBase(binary) {
45
+ return path.basename(binary).toLowerCase().replace(/\.(exe|cmd|bat|com)$/i, '');
46
+ }
47
+ function normRoot(p) {
48
+ const resolved = path.resolve(p).replace(/[\\/]+$/, '');
49
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
50
+ }
51
+ /** Canonical deterministic JSON representation signed by an ApprovalAuthProvider. */
52
+ export function serializeGrantPayload(fields) {
53
+ const resolvedScope = fields.stageScope ?? (fields.stageId ? 'stage-bound' : 'stage-independent');
54
+ return JSON.stringify({
55
+ grantId: fields.grantId,
56
+ approvedBy: fields.approvedBy,
57
+ approvedAt: fields.approvedAt,
58
+ expiresAt: fields.expiresAt,
59
+ approverIdentity: {
60
+ principalId: fields.approverIdentity.principalId,
61
+ authMethod: fields.approverIdentity.authMethod,
62
+ authenticatedAt: fields.approverIdentity.authenticatedAt,
63
+ sessionId: fields.approverIdentity.sessionId,
64
+ issuer: fields.approverIdentity.issuer ?? '',
65
+ },
66
+ operation: fields.operation,
67
+ stageId: fields.stageId ?? '',
68
+ stageScope: resolvedScope,
69
+ executable: fields.executable,
70
+ args: fields.args,
71
+ workspaceRoot: normRoot(fields.workspaceRoot),
72
+ });
73
+ }
11
74
  export function createExecutionId(prefix = 'exec') {
12
75
  return `${prefix}-${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}`;
13
76
  }
77
+ /**
78
+ * Authenticate the approver via a trusted ApprovalAuthProvider and issue a cryptographically signed grant.
79
+ * Fails closed when authentication or signing capability is unavailable.
80
+ */
81
+ export async function createApprovalGrant(input) {
82
+ if (!input.authProvider) {
83
+ throw new DevWorkspaceError('SECURITY', 'ApprovalAuthProvider is required to issue approval grants (fail-closed).');
84
+ }
85
+ if (typeof input.authProvider.signGrant !== 'function') {
86
+ throw new DevWorkspaceError('SECURITY', `ApprovalAuthProvider "${input.authProvider.id}" does not hold grant-signing capability.`);
87
+ }
88
+ const trimmedStageId = input.stageId?.trim() || undefined;
89
+ if (trimmedStageId && input.stageScope === 'stage-independent') {
90
+ throw new DevWorkspaceError('USAGE', 'Cannot specify stageScope "stage-independent" alongside a concrete stageId.');
91
+ }
92
+ if (!trimmedStageId && input.stageScope !== 'stage-independent') {
93
+ throw new DevWorkspaceError('USAGE', 'ApprovalGrant requires either a concrete stageId or explicit stageScope: "stage-independent".');
94
+ }
95
+ const stageScope = trimmedStageId ? 'stage-bound' : 'stage-independent';
96
+ const session = await input.authProvider.authenticate(input.credentials);
97
+ if (!session.principalId?.trim() || !session.sessionId?.trim()) {
98
+ throw new DevWorkspaceError('SECURITY', 'Authenticated session must supply non-empty principalId and sessionId.');
99
+ }
100
+ if (!VALID_AUTH_METHODS.has(session.authMethod)) {
101
+ throw new DevWorkspaceError('SECURITY', `Unsupported approver authentication method "${session.authMethod}".`);
102
+ }
103
+ const nowMs = Date.now();
104
+ const approvedAt = new Date(nowMs).toISOString();
105
+ const ttlMs = input.ttlMs ?? DEFAULT_GRANT_TTL_MS;
106
+ const expiresAt = input.expiresAt ?? new Date(nowMs + ttlMs).toISOString();
107
+ const approverIdentity = {
108
+ principalId: session.principalId,
109
+ authMethod: session.authMethod,
110
+ authenticatedAt: session.authenticatedAt,
111
+ sessionId: session.sessionId,
112
+ issuer: session.issuer,
113
+ };
114
+ const grantId = `grant-${nowMs.toString(36)}-${crypto.randomBytes(4).toString('hex')}`;
115
+ const canonicalPayload = serializeGrantPayload({
116
+ grantId,
117
+ approvedBy: session.principalId,
118
+ approvedAt,
119
+ expiresAt,
120
+ approverIdentity,
121
+ operation: input.operation,
122
+ stageId: trimmedStageId,
123
+ stageScope,
124
+ executable: input.executable,
125
+ args: [...input.args],
126
+ workspaceRoot: input.workspaceRoot,
127
+ });
128
+ const grantSignature = await input.authProvider.signGrant(canonicalPayload);
129
+ return {
130
+ grantId,
131
+ approvedBy: session.principalId,
132
+ approvedAt,
133
+ expiresAt,
134
+ approverIdentity,
135
+ grantSignature,
136
+ operation: input.operation,
137
+ stageId: trimmedStageId,
138
+ stageScope,
139
+ executable: input.executable,
140
+ args: [...input.args],
141
+ workspaceRoot: input.workspaceRoot,
142
+ };
143
+ }
144
+ function isValidRevokedRecord(r) {
145
+ if (!r || typeof r !== 'object' || Array.isArray(r))
146
+ return false;
147
+ const rec = r;
148
+ return (typeof rec.grantId === 'string' &&
149
+ rec.grantId.trim().length > 0 &&
150
+ typeof rec.revokedAt === 'string' &&
151
+ Number.isFinite(Date.parse(rec.revokedAt)) &&
152
+ typeof rec.revokedBy === 'string' &&
153
+ rec.revokedBy.trim().length > 0);
154
+ }
155
+ /**
156
+ * Inspect workspace revocation storage fail-closed:
157
+ * - Only missing revocation file (ENOENT) indicates zero revoked grants cleanly.
158
+ * - Permission errors, malformed JSON, non-array structures, or corrupted records return trustworthy: false.
159
+ */
160
+ export async function readRevokedGrantState(workspaceRoot) {
161
+ const revokedIds = new Set();
162
+ if (!workspaceRoot) {
163
+ return {
164
+ trustworthy: false,
165
+ revokedIds,
166
+ reason: 'Workspace root is required to verify approval grant revocation state.',
167
+ };
168
+ }
169
+ const revPath = path.join(path.resolve(workspaceRoot), REVOKED_GRANTS_REL);
170
+ let raw;
171
+ try {
172
+ raw = await fs.readFile(revPath, 'utf8');
173
+ }
174
+ catch (e) {
175
+ const code = e.code;
176
+ if (code === 'ENOENT') {
177
+ // Distinguish absent revocation file from an unreadable parent orchestration directory
178
+ try {
179
+ await fs.access(path.dirname(revPath));
180
+ }
181
+ catch (dirErr) {
182
+ const dirCode = dirErr.code;
183
+ if (dirCode && dirCode !== 'ENOENT') {
184
+ return {
185
+ trustworthy: false,
186
+ revokedIds,
187
+ reason: `Revocation directory cannot be inspected (${dirCode}): ${dirErr.message}`,
188
+ };
189
+ }
190
+ }
191
+ return { trustworthy: true, revokedIds };
192
+ }
193
+ return {
194
+ trustworthy: false,
195
+ revokedIds,
196
+ reason: `Revocation storage is unreadable (${code ?? 'IO'}): ${e.message}`,
197
+ };
198
+ }
199
+ let parsed;
200
+ try {
201
+ parsed = JSON.parse(raw.replace(/^\uFEFF/, ''));
202
+ }
203
+ catch (e) {
204
+ return {
205
+ trustworthy: false,
206
+ revokedIds,
207
+ reason: `Revocation storage contains malformed JSON: ${e.message}`,
208
+ };
209
+ }
210
+ if (!Array.isArray(parsed)) {
211
+ return {
212
+ trustworthy: false,
213
+ revokedIds,
214
+ reason: 'Revocation storage is corrupted: expected a JSON array of revocation records.',
215
+ };
216
+ }
217
+ for (let i = 0; i < parsed.length; i++) {
218
+ const item = parsed[i];
219
+ if (!isValidRevokedRecord(item)) {
220
+ return {
221
+ trustworthy: false,
222
+ revokedIds,
223
+ reason: `Revocation storage contains corrupted record at index ${i}.`,
224
+ };
225
+ }
226
+ revokedIds.add(item.grantId);
227
+ }
228
+ return { trustworthy: true, revokedIds };
229
+ }
230
+ /** Convenience wrapper that throws fail-closed if revocation storage is unreadable, malformed, or corrupted. */
231
+ export async function readRevokedGrantIds(workspaceRoot) {
232
+ const state = await readRevokedGrantState(workspaceRoot);
233
+ if (!state.trustworthy) {
234
+ throw new DevWorkspaceError('IO', state.reason ?? 'Revocation state could not be established safely.');
235
+ }
236
+ return state.revokedIds;
237
+ }
238
+ export async function revokeApprovalGrant(grant, revokedBy, reason = 'Revoked by operator', workspaceRoot) {
239
+ if (!revokedBy || !revokedBy.trim()) {
240
+ throw new DevWorkspaceError('USAGE', 'Authenticated revokedBy principal is required.');
241
+ }
242
+ const targetRoot = workspaceRoot ?? grant.workspaceRoot;
243
+ if (!targetRoot) {
244
+ throw new DevWorkspaceError('USAGE', 'Workspace root is required to persist approval grant revocation durably.');
245
+ }
246
+ return withRevocationAuthLock(targetRoot, async () => {
247
+ const state = await readRevokedGrantState(targetRoot);
248
+ if (!state.trustworthy) {
249
+ throw new DevWorkspaceError('IO', `Cannot update revocation store: ${state.reason}`);
250
+ }
251
+ const revokedAt = new Date().toISOString();
252
+ const revPath = path.join(path.resolve(targetRoot), REVOKED_GRANTS_REL);
253
+ let existing = [];
254
+ if (state.revokedIds.size > 0) {
255
+ const raw = await fs.readFile(revPath, 'utf8');
256
+ existing = JSON.parse(raw.replace(/^\uFEFF/, ''));
257
+ }
258
+ if (!existing.some((e) => e.grantId === grant.grantId)) {
259
+ existing.push({ grantId: grant.grantId, revokedAt, revokedBy, reason });
260
+ await atomicWriteJson(revPath, existing);
261
+ }
262
+ // Persist durable audit event BEFORE marking/returning completed revocation
263
+ await recordApprovalAuditEvent(targetRoot, {
264
+ timestamp: revokedAt,
265
+ agentId: revokedBy,
266
+ scope: 'terminal:exec',
267
+ target: `${grant.executable} ${grant.args.join(' ')}`.trim(),
268
+ allowed: false,
269
+ requiresApproval: true,
270
+ eventType: 'grant-revoked',
271
+ grantId: grant.grantId,
272
+ approvedBy: grant.approvedBy,
273
+ principalId: grant.approverIdentity?.principalId,
274
+ sessionId: grant.approverIdentity?.sessionId,
275
+ authMethod: grant.approverIdentity?.authMethod,
276
+ stageId: grant.stageId,
277
+ operation: grant.operation,
278
+ reason,
279
+ });
280
+ grant.revokedAt = revokedAt;
281
+ grant.revokedBy = revokedBy;
282
+ grant.revocationReason = reason;
283
+ return grant;
284
+ });
285
+ }
286
+ /**
287
+ * Durably persist a security audit event; fails closed (throws) when persistence fails.
288
+ */
289
+ export async function recordApprovalAuditEvent(workspaceRoot, entry) {
290
+ if (!workspaceRoot) {
291
+ throw new DevWorkspaceError('IO', 'Workspace root is required to durably persist security audit events.');
292
+ }
293
+ const logger = new SecurityAuditLogger(workspaceRoot);
294
+ try {
295
+ await logger.record(entry);
296
+ }
297
+ catch (err) {
298
+ throw new DevWorkspaceError('IO', `Failed to durably persist security audit event (${err.message}).`, {
299
+ cause: err,
300
+ });
301
+ }
302
+ }
303
+ /**
304
+ * Enforce strict stage-scope matching between a grant and a request:
305
+ * - A stage-bound grant MUST NOT authorize a missing or mismatched stageId.
306
+ * - A stage-independent grant MUST NOT authorize unless both grant.stageScope === 'stage-independent'
307
+ * and allowStageIndependent === true are explicitly set by policy.
308
+ */
309
+ export function evaluateStageScope(grant, requestStageId, allowStageIndependent = false) {
310
+ const reqStage = requestStageId?.trim() || undefined;
311
+ const grantStage = grant.stageId?.trim() || undefined;
312
+ if (grantStage) {
313
+ if (!reqStage) {
314
+ return {
315
+ ok: false,
316
+ reason: `Stage-scoped grant "${grant.grantId}" (bound to stage "${grantStage}") cannot authorize a request with a missing stageId.`,
317
+ };
318
+ }
319
+ if (grantStage !== reqStage) {
320
+ return {
321
+ ok: false,
322
+ reason: `Approval grant "${grant.grantId}" is scoped to stage "${grantStage}", not "${reqStage}".`,
323
+ };
324
+ }
325
+ return { ok: true };
326
+ }
327
+ if (grant.stageScope !== 'stage-independent' || !allowStageIndependent) {
328
+ return {
329
+ ok: false,
330
+ reason: `Stage-independent grant "${grant.grantId}" cannot authorize this operation without explicit policy permission (allowStageIndependent: true).`,
331
+ };
332
+ }
333
+ return { ok: true };
334
+ }
335
+ /**
336
+ * Verify grant security invariants (revocation, expiration, authenticated identity with sessionId,
337
+ * and cryptographic proof via the trusted ApprovalAuthProvider).
338
+ */
339
+ export async function verifyGrantSecurity(grant, options) {
340
+ const nowMs = options.nowMs ?? Date.now();
341
+ if (grant.revokedAt || options.revokedGrantIds?.has(grant.grantId)) {
342
+ return {
343
+ ok: false,
344
+ reason: `Approval grant "${grant.grantId}" was revoked${grant.revocationReason ? `: ${grant.revocationReason}` : ''}.`,
345
+ };
346
+ }
347
+ const expiresMs = Date.parse(grant.expiresAt);
348
+ const approvedMs = Date.parse(grant.approvedAt);
349
+ if (!Number.isFinite(expiresMs) || !Number.isFinite(approvedMs) || expiresMs < approvedMs || nowMs > expiresMs) {
350
+ return {
351
+ ok: false,
352
+ reason: `Approval grant "${grant.grantId}" has expired (${grant.expiresAt}).`,
353
+ };
354
+ }
355
+ const id = grant.approverIdentity;
356
+ if (!id ||
357
+ !id.principalId ||
358
+ id.principalId.trim().length === 0 ||
359
+ id.principalId !== grant.approvedBy ||
360
+ typeof id.sessionId !== 'string' ||
361
+ id.sessionId.trim().length === 0 ||
362
+ !VALID_AUTH_METHODS.has(id.authMethod) ||
363
+ !Number.isFinite(Date.parse(id.authenticatedAt))) {
364
+ return {
365
+ ok: false,
366
+ reason: `Approval grant "${grant.grantId}" lacks a valid authenticated approver identity and session.`,
367
+ };
368
+ }
369
+ if (!options.authProvider) {
370
+ return {
371
+ ok: false,
372
+ reason: 'Approval authentication provider is unavailable; execution fails closed.',
373
+ };
374
+ }
375
+ const sig = grant.grantSignature;
376
+ if (!sig ||
377
+ (sig.algorithm !== 'hmac-sha256' && sig.algorithm !== 'ed25519') ||
378
+ !sig.providerId ||
379
+ !sig.keyId ||
380
+ !sig.signature) {
381
+ return {
382
+ ok: false,
383
+ reason: `Approval grant "${grant.grantId}" lacks a cryptographic signature proof.`,
384
+ };
385
+ }
386
+ const payload = serializeGrantPayload({
387
+ grantId: grant.grantId,
388
+ approvedBy: grant.approvedBy,
389
+ approvedAt: grant.approvedAt,
390
+ expiresAt: grant.expiresAt,
391
+ approverIdentity: id,
392
+ operation: grant.operation,
393
+ stageId: grant.stageId,
394
+ stageScope: grant.stageScope,
395
+ executable: grant.executable,
396
+ args: grant.args,
397
+ workspaceRoot: grant.workspaceRoot,
398
+ });
399
+ let signatureValid;
400
+ try {
401
+ signatureValid = await options.authProvider.verifyGrant(payload, sig);
402
+ }
403
+ catch {
404
+ signatureValid = false;
405
+ }
406
+ if (!signatureValid) {
407
+ return {
408
+ ok: false,
409
+ reason: `Approval grant "${grant.grantId}" failed cryptographic signature verification.`,
410
+ };
411
+ }
412
+ return { ok: true };
413
+ }
414
+ /** Validate a scoped grant against operation, stage, executable, args, workspace, TTL, revocation, identity, and signature. */
415
+ export async function evaluateApprovalGrants(grants, requiredOps, cmdArgs, workspaceRoot, options = {}) {
416
+ if (!grants || grants.length === 0 || cmdArgs.length === 0) {
417
+ return { matched: false, reason: 'No approval grants supplied.' };
418
+ }
419
+ if (!options.authProvider) {
420
+ return {
421
+ matched: false,
422
+ reason: 'Approval authentication provider is unavailable; grant verification fails closed.',
423
+ };
424
+ }
425
+ const executable = cmdArgs[0];
426
+ const args = cmdArgs.slice(1);
427
+ const targetRoot = normRoot(workspaceRoot);
428
+ const nowMs = options.nowMs ?? Date.now();
429
+ const allowStageIndependent = Boolean(options.allowStageIndependent);
430
+ let lastScopeRejection;
431
+ for (const g of grants) {
432
+ if (!requiredOps.includes(g.operation))
433
+ continue;
434
+ if (normRoot(g.workspaceRoot) !== targetRoot)
435
+ continue;
436
+ if (g.executable !== executable)
437
+ continue;
438
+ if (g.args.length !== args.length || !g.args.every((val, idx) => val === args[idx]))
439
+ continue;
440
+ const stageCheck = evaluateStageScope(g, options.stageId, allowStageIndependent);
441
+ if (!stageCheck.ok) {
442
+ lastScopeRejection = stageCheck.reason;
443
+ continue;
444
+ }
445
+ const secCheck = await verifyGrantSecurity(g, {
446
+ authProvider: options.authProvider,
447
+ revokedGrantIds: options.revokedGrantIds,
448
+ nowMs,
449
+ });
450
+ if (!secCheck.ok) {
451
+ lastScopeRejection = secCheck.reason;
452
+ continue;
453
+ }
454
+ return { matched: true, grant: g };
455
+ }
456
+ return {
457
+ matched: false,
458
+ reason: lastScopeRejection ?? 'No valid non-expired, unrevoked approval grant matched this invocation.',
459
+ };
460
+ }
461
+ /** Verify whether an approval grant authorizes the exact operation, stage, executable, arguments, and workspace. */
462
+ export async function hasMatchingApprovalGrant(grants, requiredOps, cmdArgs, workspaceRoot, options = {}) {
463
+ const res = await evaluateApprovalGrants(grants, requiredOps, cmdArgs, workspaceRoot, options);
464
+ return res.matched;
465
+ }
14
466
  export function nonExecutedResponse(status, opts) {
15
467
  const safeReason = redact(opts.reason);
16
468
  const safeOutput = redact(opts.output ?? '');
@@ -59,43 +511,153 @@ export async function validateExecutionCwd(cwd, workspaceRoot) {
59
511
  }
60
512
  return { ok: true, cwd: resolvedCwd };
61
513
  }
62
- /** Enforce concrete command policy immediately before spawn (binary, shell avoidance, destructive ops). */
63
- export function validateConcreteCommand(cmdArgs, workspaceRoot, explicitApproval = false) {
514
+ function isInlineEvalFlag(arg) {
515
+ const lower = arg.toLowerCase();
516
+ return (lower === '-e' ||
517
+ lower === '--eval' ||
518
+ lower.startsWith('--eval=') ||
519
+ lower === '-p' ||
520
+ lower === '--print' ||
521
+ lower === '-c' ||
522
+ lower === '--command' ||
523
+ lower === '--input-type' ||
524
+ lower.startsWith('--input-type=') ||
525
+ lower === '-');
526
+ }
527
+ /**
528
+ * Enforce concrete command policy immediately before spawn:
529
+ * - Never allows shells, NUL bytes, or absolute-path policy bypasses.
530
+ * - Restricts arbitrary inline eval flags on interpreters unless bound by exact ApprovalGrant.
531
+ * - Requires exact scoped ApprovalGrant for destructive commands or non-allowlisted binaries.
532
+ */
533
+ export async function validateConcreteCommand(cmdArgs, workspaceRoot, opts = {}) {
64
534
  const binary = cmdArgs[0];
65
535
  if (!binary || !binary.trim()) {
66
536
  return { ok: false, reason: 'Empty executable command cannot be invoked.' };
67
537
  }
68
- const base = path.basename(binary).toLowerCase();
69
- if (SHELL_BINARIES.has(base)) {
70
- return { ok: false, reason: `Direct shell invocation "${base}" is disallowed; pass an executable with argument array instead.` };
71
- }
72
538
  if (cmdArgs.some((arg) => arg.includes('\0'))) {
73
539
  return { ok: false, reason: 'Command arguments contain NUL byte.' };
74
540
  }
75
- if (!explicitApproval) {
76
- // Only check executable + flag patterns outside quoted payload arguments for shell binaries; block direct destructive commands.
77
- const headAndFlags = `${base} ${cmdArgs.slice(1).filter((a) => !a.includes(' ')).join(' ')}`;
78
- if (DESTRUCTIVE_EXEC_RE.test(headAndFlags)) {
79
- return { ok: false, reason: `Destructive command "${base}" requires explicit developer approval before execution.` };
541
+ const rawBase = path.basename(binary).toLowerCase();
542
+ const base = normalizeExeBase(binary);
543
+ if (SHELL_BINARIES.has(rawBase) || SHELL_BINARIES.has(base)) {
544
+ return { ok: false, reason: `Direct shell invocation "${rawBase}" is disallowed; pass an allowlisted executable with argument array instead.` };
545
+ }
546
+ let revokedIds;
547
+ if (opts.revocationState) {
548
+ if (!opts.revocationState.trustworthy) {
549
+ return {
550
+ ok: false,
551
+ reason: `Execution blocked: ${opts.revocationState.reason ?? 'revocation state cannot be trusted.'}`,
552
+ };
553
+ }
554
+ revokedIds = opts.revocationState.revokedIds;
555
+ }
556
+ else if (opts.revokedGrantIds) {
557
+ revokedIds = opts.revokedGrantIds;
558
+ }
559
+ else {
560
+ const revState = await readRevokedGrantState(workspaceRoot);
561
+ if (!revState.trustworthy) {
562
+ return {
563
+ ok: false,
564
+ reason: `Execution blocked: ${revState.reason ?? 'revocation state cannot be trusted.'}`,
565
+ };
566
+ }
567
+ revokedIds = revState.revokedIds;
568
+ }
569
+ const grantEvalOpts = {
570
+ stageId: opts.stageId,
571
+ revokedGrantIds: revokedIds,
572
+ authProvider: opts.authProvider,
573
+ allowStageIndependent: opts.allowStageIndependent,
574
+ };
575
+ let matchedGrant;
576
+ // Check if explicit grant is required for this invocation kind (e.g., external-agent)
577
+ if (opts.requireGrantForOps && opts.requireGrantForOps.length > 0) {
578
+ const evalRes = await evaluateApprovalGrants(opts.approvalGrants, opts.requireGrantForOps, cmdArgs, workspaceRoot, grantEvalOpts);
579
+ if (!evalRes.matched) {
580
+ return { ok: false, reason: evalRes.reason ?? `Execution of "${base}" requires an exact valid approval grant.` };
80
581
  }
81
- const evaluator = new SecurityPolicyEvaluator(workspaceRoot);
82
- // If invoking an explicit script/command inside an allowlisted tool (node/npm/npx/git) check evaluator on binary; block arbitrary shells/installers.
83
- const basePolicy = evaluator.checkCommandExec(base);
84
- const allowedRuntimeBins = new Set(['node', 'node.exe', 'npm', 'npx', 'git', 'vitest', 'tsc', 'claude', 'codex', 'cursor']);
85
- if (!basePolicy.allowed && !allowedRuntimeBins.has(base) && !path.isAbsolute(binary)) {
86
- return { ok: false, reason: basePolicy.reason ?? `Executable "${base}" is not permitted by execution policy.` };
582
+ matchedGrant = evalRes.grant;
583
+ }
584
+ // Check destructive commands / binaries (cannot be authorized by blanket booleans)
585
+ const headAndFlags = `${base} ${cmdArgs.slice(1).filter((a) => !a.includes(' ')).join(' ')}`;
586
+ if (DESTRUCTIVE_BIN_BASES.has(base) || DESTRUCTIVE_EXEC_RE.test(headAndFlags)) {
587
+ const evalRes = await evaluateApprovalGrants(opts.approvalGrants, ['destructive-op'], cmdArgs, workspaceRoot, grantEvalOpts);
588
+ if (!evalRes.matched) {
589
+ return { ok: false, reason: evalRes.reason ?? `Destructive operation "${base}" blocked: requires an exact valid destructive-op approval grant.` };
87
590
  }
591
+ matchedGrant = evalRes.grant;
88
592
  }
89
- return { ok: true };
593
+ // Check interpreter inline-code execution and script path confinement
594
+ if (INTERPRETER_BASES.has(base)) {
595
+ const args = cmdArgs.slice(1);
596
+ const usesInlineEval = args.some((a) => isInlineEvalFlag(a));
597
+ if (usesInlineEval) {
598
+ const evalRes = await evaluateApprovalGrants(opts.approvalGrants, ['command-exec', 'external-agent', 'destructive-op'], cmdArgs, workspaceRoot, grantEvalOpts);
599
+ if (!evalRes.matched) {
600
+ return { ok: false, reason: evalRes.reason ?? `Arbitrary inline interpreter execution via "${base}" is blocked without an exact valid approval grant.` };
601
+ }
602
+ matchedGrant = evalRes.grant;
603
+ }
604
+ else {
605
+ const scriptArg = args.find((a) => !a.startsWith('-'));
606
+ if (scriptArg) {
607
+ const resolvedScript = path.isAbsolute(scriptArg) ? path.resolve(scriptArg) : path.resolve(workspaceRoot, scriptArg);
608
+ if (!isInside(path.resolve(workspaceRoot), resolvedScript)) {
609
+ return { ok: false, reason: `Interpreter script "${scriptArg}" resolves outside workspace root.` };
610
+ }
611
+ try {
612
+ await assertNoSymlinkEscape(path.resolve(workspaceRoot), resolvedScript);
613
+ }
614
+ catch (e) {
615
+ return { ok: false, reason: e.message };
616
+ }
617
+ }
618
+ }
619
+ return { ok: true, matchedGrant };
620
+ }
621
+ // Enforce executable allowlist even when binary is specified as an absolute path
622
+ const evaluator = new SecurityPolicyEvaluator(workspaceRoot);
623
+ const policyCheck = evaluator.checkCommandExec(cmdArgs.join(' '));
624
+ const isAllowlistedTool = ALLOWED_TOOL_BASES.has(base);
625
+ if (!isAllowlistedTool && !policyCheck.allowed) {
626
+ const evalRes = await evaluateApprovalGrants(opts.approvalGrants, ['command-exec', 'external-agent', 'destructive-op'], cmdArgs, workspaceRoot, grantEvalOpts);
627
+ if (!evalRes.matched) {
628
+ return { ok: false, reason: evalRes.reason ?? policyCheck.reason ?? `Executable "${binary}" is not in the execution allowlist and lacks a valid approval grant.` };
629
+ }
630
+ matchedGrant = evalRes.grant;
631
+ }
632
+ return { ok: true, matchedGrant };
90
633
  }
91
- /** Execute a concrete validated command with minimal env, bounded redacted output, and tree cleanup. */
92
- export async function executeBoundedCommand(request, cmdArgs, executionKind, defaultTimeoutMs, untrustedOutput = false) {
634
+ /** Execute a concrete validated command with minimal env, immediate pre-spawn grant revalidation, audit events, and full snapshot capture. */
635
+ export async function executeBoundedCommand(request, cmdArgs, executionKind, defaultTimeoutMs, untrustedOutput = false, requiredGrantOps) {
93
636
  const executionId = createExecutionId(executionKind);
94
637
  const startMs = Date.now();
95
638
  const startedAt = new Date(startMs).toISOString();
96
639
  const targetCwd = request.sandboxPath ?? request.cwd;
640
+ const effectiveRoot = request.workspaceRoot ?? targetCwd;
97
641
  const cwdCheck = await validateExecutionCwd(targetCwd, request.workspaceRoot);
98
642
  if (!cwdCheck.ok) {
643
+ if (request.workspaceRoot) {
644
+ try {
645
+ await recordApprovalAuditEvent(request.workspaceRoot, {
646
+ timestamp: new Date().toISOString(),
647
+ agentId: request.agentId,
648
+ scope: 'terminal:exec',
649
+ target: cmdArgs.join(' '),
650
+ allowed: false,
651
+ requiresApproval: true,
652
+ eventType: 'grant-rejected',
653
+ stageId: request.stageId,
654
+ reason: cwdCheck.reason,
655
+ });
656
+ }
657
+ catch {
658
+ // Execution is already blocked; do not emit unhandled rejection after block
659
+ }
660
+ }
99
661
  return nonExecutedResponse('BLOCKED', {
100
662
  executionKind: 'none',
101
663
  reason: cwdCheck.reason,
@@ -103,24 +665,144 @@ export async function executeBoundedCommand(request, cmdArgs, executionKind, def
103
665
  cwd: targetCwd,
104
666
  });
105
667
  }
106
- const cmdCheck = validateConcreteCommand(cmdArgs, request.workspaceRoot ?? targetCwd ?? process.cwd(), request.explicitApproval);
107
- if (!cmdCheck.ok) {
668
+ const snapRoot = effectiveRoot ?? cwdCheck.cwd;
669
+ // Hold the shared revocation/authorization lock continuously across revocation check,
670
+ // cryptographic grant validation, durable audit persistence, pre-spawn snapshot, and process spawn creation.
671
+ let criticalSection;
672
+ try {
673
+ criticalSection = await withRevocationAuthLock(effectiveRoot, async () => {
674
+ const revocationState = await readRevokedGrantState(effectiveRoot);
675
+ if (!revocationState.trustworthy) {
676
+ let auditNote = '';
677
+ if (effectiveRoot) {
678
+ try {
679
+ await recordApprovalAuditEvent(effectiveRoot, {
680
+ timestamp: new Date().toISOString(),
681
+ agentId: request.agentId,
682
+ scope: 'terminal:exec',
683
+ target: cmdArgs.join(' '),
684
+ allowed: false,
685
+ requiresApproval: true,
686
+ eventType: 'grant-rejected',
687
+ stageId: request.stageId,
688
+ reason: revocationState.reason,
689
+ });
690
+ }
691
+ catch (auditErr) {
692
+ auditNote = ` (audit log error: ${auditErr.message})`;
693
+ }
694
+ }
695
+ return {
696
+ ok: false,
697
+ response: nonExecutedResponse('BLOCKED', {
698
+ executionKind: 'none',
699
+ reason: `Execution blocked because revocation state cannot be established cleanly: ${revocationState.reason}${auditNote}`,
700
+ remediation: 'Restore or repair .devworkspace/orchestration/revoked-grants.json permissions and valid JSON array contents.',
701
+ cwd: cwdCheck.cwd,
702
+ }),
703
+ };
704
+ }
705
+ const cmdCheck = await validateConcreteCommand(cmdArgs, effectiveRoot ?? process.cwd(), {
706
+ approvalGrants: request.approvalGrants,
707
+ stageId: request.stageId,
708
+ requireGrantForOps: requiredGrantOps,
709
+ revocationState,
710
+ authProvider: request.authProvider,
711
+ allowStageIndependent: request.allowStageIndependent,
712
+ });
713
+ if (!cmdCheck.ok) {
714
+ if (effectiveRoot) {
715
+ try {
716
+ await recordApprovalAuditEvent(effectiveRoot, {
717
+ timestamp: new Date().toISOString(),
718
+ agentId: request.agentId,
719
+ scope: 'terminal:exec',
720
+ target: cmdArgs.join(' '),
721
+ allowed: false,
722
+ requiresApproval: true,
723
+ eventType: 'grant-rejected',
724
+ stageId: request.stageId,
725
+ reason: cmdCheck.reason,
726
+ });
727
+ }
728
+ catch {
729
+ // Execution is already blocked
730
+ }
731
+ }
732
+ return {
733
+ ok: false,
734
+ response: nonExecutedResponse('BLOCKED', {
735
+ executionKind: 'none',
736
+ reason: cmdCheck.reason,
737
+ remediation: 'Bind a valid non-expired, unrevoked approval grant or use an allowlisted non-shell executable inside the workspace.',
738
+ cwd: cwdCheck.cwd,
739
+ }),
740
+ };
741
+ }
742
+ // Security-sensitive executions and granted invocations MUST durably persist audit log before spawning
743
+ const requiresDurableAudit = Boolean(cmdCheck.matchedGrant ||
744
+ executionKind === 'agent' ||
745
+ (requiredGrantOps && requiredGrantOps.length > 0));
746
+ if (requiresDurableAudit) {
747
+ try {
748
+ await recordApprovalAuditEvent(effectiveRoot, {
749
+ timestamp: new Date().toISOString(),
750
+ agentId: request.agentId,
751
+ scope: 'terminal:exec',
752
+ target: cmdArgs.join(' '),
753
+ allowed: true,
754
+ requiresApproval: Boolean(cmdCheck.matchedGrant),
755
+ eventType: cmdCheck.matchedGrant ? 'grant-validated' : 'command-policy',
756
+ grantId: cmdCheck.matchedGrant?.grantId,
757
+ approvedBy: cmdCheck.matchedGrant?.approvedBy,
758
+ principalId: cmdCheck.matchedGrant?.approverIdentity.principalId,
759
+ sessionId: cmdCheck.matchedGrant?.approverIdentity.sessionId,
760
+ authMethod: cmdCheck.matchedGrant?.approverIdentity.authMethod,
761
+ stageId: cmdCheck.matchedGrant?.stageId ?? request.stageId,
762
+ operation: cmdCheck.matchedGrant?.operation,
763
+ });
764
+ }
765
+ catch (auditErr) {
766
+ return {
767
+ ok: false,
768
+ response: nonExecutedResponse('BLOCKED', {
769
+ executionKind: 'none',
770
+ reason: `Execution blocked because durable security audit logging failed: ${auditErr.message}`,
771
+ remediation: 'Ensure the workspace audit log path (.devworkspace/orchestration/security-audit.jsonl) is writable.',
772
+ cwd: cwdCheck.cwd,
773
+ }),
774
+ };
775
+ }
776
+ }
777
+ const beforeSnapshot = await captureWorkspaceSnapshotDetailed(snapRoot);
778
+ const safeEnv = createMinimalExecutionEnv(process.env, request.allowlistedEnvKeys, request.env);
779
+ const started = startRun(cmdArgs[0], cmdArgs.slice(1), {
780
+ cwd: cwdCheck.cwd,
781
+ timeoutMs: request.timeoutMs ?? defaultTimeoutMs,
782
+ signal: request.signal,
783
+ maxBytes: request.maxBytes ?? MAX_RUNTIME_OUTPUT_CHARS,
784
+ env: safeEnv,
785
+ replaceEnv: true,
786
+ });
787
+ return { ok: true, beforeSnapshot, started };
788
+ });
789
+ }
790
+ catch (lockErr) {
108
791
  return nonExecutedResponse('BLOCKED', {
109
792
  executionKind: 'none',
110
- reason: cmdCheck.reason,
111
- remediation: 'Approve destructive operations explicitly or use an allowlisted non-shell executable.',
793
+ reason: `Execution blocked because revocation/authorization lock could not be acquired cleanly: ${lockErr.message}`,
794
+ remediation: 'Ensure .devworkspace/local/ is writable and retry once conflicting workspace locks clear.',
112
795
  cwd: cwdCheck.cwd,
113
796
  });
114
797
  }
115
- const safeEnv = createMinimalExecutionEnv(process.env, request.allowlistedEnvKeys, request.env);
116
- const res = await run(cmdArgs[0], cmdArgs.slice(1), {
117
- cwd: cwdCheck.cwd,
118
- timeoutMs: request.timeoutMs ?? defaultTimeoutMs,
119
- signal: request.signal,
120
- maxBytes: request.maxBytes ?? MAX_RUNTIME_OUTPUT_CHARS,
121
- env: safeEnv,
122
- replaceEnv: true,
123
- });
798
+ if (!criticalSection.ok) {
799
+ return criticalSection.response;
800
+ }
801
+ const { beforeSnapshot, started } = criticalSection;
802
+ const res = await started.done;
803
+ const afterSnapshot = await captureWorkspaceSnapshotDetailed(snapRoot);
804
+ const gitRenames = await detectGitRenames(snapRoot);
805
+ const changeManifest = diffWorkspaceSnapshots(beforeSnapshot, afterSnapshot, gitRenames);
124
806
  const endedAt = new Date().toISOString();
125
807
  const durationMs = Date.now() - startMs;
126
808
  const boundedStdout = redact(res.stdout.slice(0, MAX_RUNTIME_OUTPUT_CHARS));
@@ -150,7 +832,8 @@ export async function executeBoundedCommand(request, cmdArgs, executionKind, def
150
832
  endedAt,
151
833
  durationMs,
152
834
  tokensUsed: 0,
153
- filesModified: status === 'SUCCEEDED' ? (request.contextFiles ?? []) : [],
835
+ filesModified: changeManifest.changedFiles,
836
+ changeManifest,
154
837
  exitCode: res.code ?? (status === 'SUCCEEDED' ? 0 : 1),
155
838
  stdout: boundedStdout,
156
839
  stderr: boundedStderr,
@@ -160,4 +843,3 @@ export async function executeBoundedCommand(request, cmdArgs, executionKind, def
160
843
  sandboxCapability: 'unavailable-cwd-only',
161
844
  };
162
845
  }
163
- //# sourceMappingURL=boundary.js.map