devworkspace 0.5.0 → 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 (384) hide show
  1. package/CHANGELOG.md +44 -0
  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 +21 -3
  81. package/dist/intelligence/orchestration/engine.js +486 -48
  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 +40 -2
  85. package/dist/intelligence/orchestration/types.js +2 -3
  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 +21 -33
  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 +142 -0
  94. package/dist/intelligence/runtime/boundary.js +845 -0
  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 +38 -61
  99. package/dist/intelligence/runtime/native.js +23 -56
  100. package/dist/intelligence/runtime/types.d.ts +91 -1
  101. package/dist/intelligence/runtime/types.js +11 -2
  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 +30 -8
  111. package/dist/intelligence/verification/engine.js +126 -21
  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 +71 -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.d.ts +1 -0
  169. package/dist/standards/distribution/cache.js +199 -186
  170. package/dist/standards/distribution/index.js +0 -1
  171. package/dist/standards/distribution/keys.js +0 -1
  172. package/dist/standards/distribution/package.js +6 -1
  173. package/dist/standards/distribution/server.js +0 -1
  174. package/dist/standards/distribution/sync.d.ts +7 -2
  175. package/dist/standards/distribution/sync.js +41 -9
  176. package/dist/standards/distribution/types.js +0 -1
  177. package/dist/standards/engine/compliance.js +0 -1
  178. package/dist/standards/engine/engine.js +0 -1
  179. package/dist/standards/engine/reporter.js +0 -1
  180. package/dist/standards/index.js +0 -1
  181. package/dist/standards/registry/registry.js +0 -1
  182. package/dist/standards/schema/types.js +0 -1
  183. package/dist/standards/schema/validate.js +0 -1
  184. package/dist/standards/templates/index.js +0 -1
  185. package/dist/standards/validators/database.js +0 -1
  186. package/dist/standards/validators/quality.js +0 -1
  187. package/dist/standards/validators/registry.js +0 -1
  188. package/dist/standards/validators/security.js +0 -1
  189. package/dist/standards/validators/testing.js +0 -1
  190. package/dist/standards/validators/types.js +0 -1
  191. package/dist/standards/validators/undo-kit.js +0 -1
  192. package/dist/tasks/routing.js +0 -1
  193. package/dist/tasks/task.js +0 -1
  194. package/dist/utils/cleanup.js +0 -1
  195. package/dist/utils/fs.js +0 -1
  196. package/dist/utils/lock.js +92 -49
  197. package/dist/utils/logger.js +0 -1
  198. package/dist/utils/paths.js +0 -1
  199. package/dist/utils/proc.d.ts +12 -0
  200. package/dist/utils/proc.js +106 -44
  201. package/dist/verification/safety.js +0 -1
  202. package/dist/verification/scope.js +0 -1
  203. package/docs/agents.md +15 -0
  204. package/docs/architecture/global-standards-architecture.md +287 -0
  205. package/docs/archive/global-standards/GLOBAL_STANDARDS_AUDIT.md +99 -0
  206. package/docs/archive/global-standards/GLOBAL_STANDARDS_FINAL_STATUS.md +138 -0
  207. package/docs/archive/global-standards/GLOBAL_STANDARDS_IMPLEMENTATION_PLAN.md +100 -0
  208. package/docs/archive/global-standards/GLOBAL_STANDARDS_INDEPENDENT_AUDIT.md +219 -0
  209. package/docs/archive/global-standards/GLOBAL_STANDARDS_SECURITY_REPORT.md +184 -0
  210. package/docs/configuration.md +67 -0
  211. package/docs/contributing.md +15 -5
  212. package/docs/development/EXECUTION_STATE.md +50 -0
  213. package/docs/features.md +80 -0
  214. package/docs/getting-started.md +69 -111
  215. package/docs/guides/global-standards-migration.md +100 -0
  216. package/docs/integrations.md +7 -0
  217. package/docs/mcp.md +13 -0
  218. package/docs/security/THIRD_PARTY_LICENSES.md +41 -0
  219. package/docs/security.md +8 -2
  220. package/docs/testing/FINAL_CORRECTION_AND_CLEANUP_REPORT.md +92 -0
  221. package/docs/testing/global-standards-real-project-tests.md +218 -0
  222. package/docs/testing/global-standards-test-report.md +89 -0
  223. package/docs/testing/global-standards-verification-matrix.md +174 -0
  224. package/docs/troubleshooting.md +3 -0
  225. package/package.json +1 -1
  226. package/dist/agents/claude/adapter.js.map +0 -1
  227. package/dist/agents/claude/content.js.map +0 -1
  228. package/dist/agents/codex/adapter.js.map +0 -1
  229. package/dist/agents/copilot/adapter.js.map +0 -1
  230. package/dist/agents/cursor/adapter.js.map +0 -1
  231. package/dist/agents/index.js.map +0 -1
  232. package/dist/agents/shared.js.map +0 -1
  233. package/dist/agents/types.js.map +0 -1
  234. package/dist/cli/args.js.map +0 -1
  235. package/dist/cli/help.js.map +0 -1
  236. package/dist/cli/main.js.map +0 -1
  237. package/dist/cli/render.js.map +0 -1
  238. package/dist/cli/run.js.map +0 -1
  239. package/dist/config/schemas.js.map +0 -1
  240. package/dist/config/validate.js.map +0 -1
  241. package/dist/core/artifacts.js.map +0 -1
  242. package/dist/core/contracts.js.map +0 -1
  243. package/dist/core/migrations.js.map +0 -1
  244. package/dist/core/version.js.map +0 -1
  245. package/dist/core/versioned.js.map +0 -1
  246. package/dist/core/workspace.js.map +0 -1
  247. package/dist/decisions/decision.js.map +0 -1
  248. package/dist/discovery/cache.js.map +0 -1
  249. package/dist/discovery/commands.js.map +0 -1
  250. package/dist/discovery/detect.js.map +0 -1
  251. package/dist/discovery/docs.js.map +0 -1
  252. package/dist/discovery/entrypoints.js.map +0 -1
  253. package/dist/discovery/ignore.js.map +0 -1
  254. package/dist/discovery/scan.js.map +0 -1
  255. package/dist/discovery/types.js.map +0 -1
  256. package/dist/dx/dashboard.js.map +0 -1
  257. package/dist/dx/guidance.js.map +0 -1
  258. package/dist/dx/index.js.map +0 -1
  259. package/dist/dx/onboarding.js.map +0 -1
  260. package/dist/dx/types.js.map +0 -1
  261. package/dist/errors/index.js.map +0 -1
  262. package/dist/features/schema.js.map +0 -1
  263. package/dist/features/types.js.map +0 -1
  264. package/dist/features/validate.js.map +0 -1
  265. package/dist/git/git.js.map +0 -1
  266. package/dist/index.js.map +0 -1
  267. package/dist/integrations/adapters/agent-skills.js.map +0 -1
  268. package/dist/integrations/adapters/claudePlugin.js.map +0 -1
  269. package/dist/integrations/adapters/graphify.js.map +0 -1
  270. package/dist/integrations/adapters/omniroute.js.map +0 -1
  271. package/dist/integrations/adapters/pluginSkill.js.map +0 -1
  272. package/dist/integrations/adapters/ponytail.js.map +0 -1
  273. package/dist/integrations/exec.js.map +0 -1
  274. package/dist/integrations/index.js.map +0 -1
  275. package/dist/integrations/manager.js.map +0 -1
  276. package/dist/integrations/notices.js.map +0 -1
  277. package/dist/integrations/persistentPath.js.map +0 -1
  278. package/dist/integrations/protect.js.map +0 -1
  279. package/dist/integrations/state.js.map +0 -1
  280. package/dist/integrations/types.js.map +0 -1
  281. package/dist/intelligence/agents/profiles.js.map +0 -1
  282. package/dist/intelligence/agents/registry.js.map +0 -1
  283. package/dist/intelligence/agents/types.js.map +0 -1
  284. package/dist/intelligence/observability/tracer.js.map +0 -1
  285. package/dist/intelligence/observability/types.js.map +0 -1
  286. package/dist/intelligence/orchestration/engine.js.map +0 -1
  287. package/dist/intelligence/orchestration/lock-manager.js.map +0 -1
  288. package/dist/intelligence/orchestration/store.js.map +0 -1
  289. package/dist/intelligence/orchestration/types.js.map +0 -1
  290. package/dist/intelligence/routing/matcher.js.map +0 -1
  291. package/dist/intelligence/routing/router.js.map +0 -1
  292. package/dist/intelligence/routing/types.js.map +0 -1
  293. package/dist/intelligence/runtime/adk/adapter.js.map +0 -1
  294. package/dist/intelligence/runtime/adk/detector.js.map +0 -1
  295. package/dist/intelligence/runtime/external.js.map +0 -1
  296. package/dist/intelligence/runtime/native.js.map +0 -1
  297. package/dist/intelligence/runtime/types.js.map +0 -1
  298. package/dist/intelligence/security/audit.js.map +0 -1
  299. package/dist/intelligence/security/policy.js.map +0 -1
  300. package/dist/intelligence/security/types.js.map +0 -1
  301. package/dist/intelligence/skills/builtins.js.map +0 -1
  302. package/dist/intelligence/skills/loader.js.map +0 -1
  303. package/dist/intelligence/skills/registry.js.map +0 -1
  304. package/dist/intelligence/skills/types.js.map +0 -1
  305. package/dist/intelligence/verification/engine.js.map +0 -1
  306. package/dist/intelligence/verification/reviewer.js.map +0 -1
  307. package/dist/intelligence/verification/types.js.map +0 -1
  308. package/dist/knowledge/facts.js.map +0 -1
  309. package/dist/mcp/protocol.js.map +0 -1
  310. package/dist/mcp/server.js.map +0 -1
  311. package/dist/mcp/setup.js.map +0 -1
  312. package/dist/mcp/tools.js.map +0 -1
  313. package/dist/mcp/types.js.map +0 -1
  314. package/dist/mcp/verify.js.map +0 -1
  315. package/dist/portability/bundle.js.map +0 -1
  316. package/dist/prompts/onboarding.js.map +0 -1
  317. package/dist/prompts/refresh.js.map +0 -1
  318. package/dist/prompts/requirements.js.map +0 -1
  319. package/dist/security/files.js.map +0 -1
  320. package/dist/security/redact.js.map +0 -1
  321. package/dist/services/agent.js.map +0 -1
  322. package/dist/services/analysis.js.map +0 -1
  323. package/dist/services/common.js.map +0 -1
  324. package/dist/services/doctor.js.map +0 -1
  325. package/dist/services/drift.js.map +0 -1
  326. package/dist/services/features.js.map +0 -1
  327. package/dist/services/graph.js.map +0 -1
  328. package/dist/services/init.js.map +0 -1
  329. package/dist/services/integrations.js.map +0 -1
  330. package/dist/services/intelligence.js.map +0 -1
  331. package/dist/services/knowledge.js.map +0 -1
  332. package/dist/services/migrate.js.map +0 -1
  333. package/dist/services/portability.js.map +0 -1
  334. package/dist/services/records.js.map +0 -1
  335. package/dist/services/refresh.js.map +0 -1
  336. package/dist/services/reset.js.map +0 -1
  337. package/dist/services/setup.js.map +0 -1
  338. package/dist/services/standards.js.map +0 -1
  339. package/dist/services/status.js.map +0 -1
  340. package/dist/services/taskContext.js.map +0 -1
  341. package/dist/services/tasks.js.map +0 -1
  342. package/dist/services/verify.js.map +0 -1
  343. package/dist/sessions/session.js.map +0 -1
  344. package/dist/standards/acquisition/ingest.js.map +0 -1
  345. package/dist/standards/applicability/engine.js.map +0 -1
  346. package/dist/standards/builtin/code-quality.js.map +0 -1
  347. package/dist/standards/builtin/database-safety.js.map +0 -1
  348. package/dist/standards/builtin/index.js.map +0 -1
  349. package/dist/standards/builtin/security-baseline.js.map +0 -1
  350. package/dist/standards/builtin/testing-contracts.js.map +0 -1
  351. package/dist/standards/builtin/undo-kit.js.map +0 -1
  352. package/dist/standards/config/config.js.map +0 -1
  353. package/dist/standards/distribution/cache.js.map +0 -1
  354. package/dist/standards/distribution/index.js.map +0 -1
  355. package/dist/standards/distribution/keys.js.map +0 -1
  356. package/dist/standards/distribution/package.js.map +0 -1
  357. package/dist/standards/distribution/server.js.map +0 -1
  358. package/dist/standards/distribution/sync.js.map +0 -1
  359. package/dist/standards/distribution/types.js.map +0 -1
  360. package/dist/standards/engine/compliance.js.map +0 -1
  361. package/dist/standards/engine/engine.js.map +0 -1
  362. package/dist/standards/engine/reporter.js.map +0 -1
  363. package/dist/standards/index.js.map +0 -1
  364. package/dist/standards/registry/registry.js.map +0 -1
  365. package/dist/standards/schema/types.js.map +0 -1
  366. package/dist/standards/schema/validate.js.map +0 -1
  367. package/dist/standards/templates/index.js.map +0 -1
  368. package/dist/standards/validators/database.js.map +0 -1
  369. package/dist/standards/validators/quality.js.map +0 -1
  370. package/dist/standards/validators/registry.js.map +0 -1
  371. package/dist/standards/validators/security.js.map +0 -1
  372. package/dist/standards/validators/testing.js.map +0 -1
  373. package/dist/standards/validators/types.js.map +0 -1
  374. package/dist/standards/validators/undo-kit.js.map +0 -1
  375. package/dist/tasks/routing.js.map +0 -1
  376. package/dist/tasks/task.js.map +0 -1
  377. package/dist/utils/cleanup.js.map +0 -1
  378. package/dist/utils/fs.js.map +0 -1
  379. package/dist/utils/lock.js.map +0 -1
  380. package/dist/utils/logger.js.map +0 -1
  381. package/dist/utils/paths.js.map +0 -1
  382. package/dist/utils/proc.js.map +0 -1
  383. package/dist/verification/safety.js.map +0 -1
  384. package/dist/verification/scope.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"undo-kit.js","sourceRoot":"","sources":["../../../src/standards/validators/undo-kit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,IAAI,MAAM,WAAW,CAAC;AAI7B,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,GAAqB;IAC9D,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,EAAE,EAAE,IAAI,0BAA0B,CAAC;IAC1D,MAAM,UAAU,GAAG,GAAG,CAAC,QAAQ,EAAE,EAAE,IAAI,gCAAgC,CAAC;IACxE,MAAM,KAAK,GAAG,GAAG,CAAC,IAAI,EAAE,KAAK,IAAI,0BAA0B,CAAC;IAC5D,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,EAAE,QAAQ,IAAI,MAAM,CAAC;IAE9C,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,YAAY,EAAE,aAAa,CAAC,CAAC;IAChE,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QAC9B,OAAO;YACL,MAAM;YACN,UAAU;YACV,KAAK;YACL,MAAM,EAAE,MAAM;YACd,MAAM,EAAE,KAAK;YACb,QAAQ;YACR,OAAO,EAAE,2CAA2C;YACpD,QAAQ,EAAE,EAAE,IAAI,E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a,CAAC,CAAC;IAChE,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;QAC9B,OAAO;YACL,MAAM;YACN,UAAU;YACV,KAAK;YACL,MAAM,EAAE,SAAS;YACjB,MAAM,EAAE,KAAK;YACb,QAAQ;YACR,OAAO,EAAE,kEAAkE;SAC5E,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;IACxD,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAEpC,MAAM,oBAAoB,GACxB,KAAK,CAAC,QAAQ,CAAC,eAAe,CAAC;QAC/B,CAAC,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC;IAE5G,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAC1B,OAAO;YACL,MAAM;YACN,UAAU;YACV,KAAK;YACL,MAAM,EAAE,MAAM;YACd,MAAM,EAAE,KAAK;YACb,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,8DAA8D;YACvE,QAAQ,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE;YACjC,WAAW,EACT,kIAAkI;SACrI,CAAC;IACJ,CAAC;IAED,OAAO;QACL,MAAM;QACN,UAAU;QACV,KAAK;QACL,MAAM,EAAE,MAAM;QACd,MAAM,EAAE,IAAI;QACZ,QAAQ;QACR,OAAO,EAAE,iDAAiD;QAC1D,QAAQ,EAAE,EAAE,IAAI,EAAE,aAAa,EAAE;KAClC,CAAC;AACJ,CAAC","sourcesContent":["import { existsSync, promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type { ValidationResult } from '../schema/types.js';\nimport type { ValidatorContext } from './types.js';\n\nexport async function validateRollbackPlan(ctx: ValidatorContext): Promise<ValidationResult> {\n const ruleId = ctx.rule?.id ?? 'deployment.rollback-plan';\n const standardId = ctx.standard?.id ?? 'deployment-safety-and-rollback';\n const title = ctx.rule?.title ?? 'Rollback Plan Documented';\n const severity = ctx.rule?.severity ?? 'high';\n\n const rollbackPath = path.join(ctx.workspaceDir, 'ROLLBACK.md');\n if (!existsSync(rollbackPath)) {\n return {\n ruleId,\n standardId,\n title,\n status: 'FAIL',\n passed: false,\n severity,\n message: 'ROLLBACK.md is missing from project root.',\n evidence: { file: 'ROLLBACK.md' },\n remediation:\n 'Create ROLLBACK.md at the project root using the Undo Kit template. Run \"devworkspace standards apply deployment-safety-and-rollback\" to generate it.',\n };\n }\n\n try {\n const content = await fs.readFile(rollbackPath, 'utf8');\n const lower = content.toLowerCase();\n\n const missingSections: string[] = [];\n if (!lower.includes('hosting') && !lower.includes('deploy')) missingSections.push('Hosting Rollback (Button 1)');\n if (!lower.includes('backup') && !lower.includes('database')) missingSections.push('Database Backup (Button 2)');\n if (!lower.includes('switch') && !lower.includes('flag')) missingSections.push('Feature Switch (Button 3)');\n if (!lower.includes('practice') && !lower.includes('rehearsal')) missingSections.push('Recovery Rehearsal (Button 4)');\n\n if (missingSections.length > 0) {\n return {\n ruleId,\n standardId,\n title,\n status: 'WARN',\n passed: false,\n severity: 'medium',\n message: `ROLLBACK.md is present but missing required Undo Kit sections: ${missingSections.join(', ')}.`,\n evidence: { file: 'ROLLBACK.md' },\n remediation: 'Update ROLLBACK.md to cover all 4 Undo Kit buttons: Hosting Deploy, Backup First, Feature Switch, and Rehearsal.',\n };\n }\n\n return {\n ruleId,\n standardId,\n title,\n status: 'PASS',\n passed: true,\n severity,\n message: 'ROLLBACK.md is present and contains all required Undo Kit operational sections.',\n evidence: { file: 'ROLLBACK.md' },\n };\n } catch (e) {\n return {\n ruleId,\n standardId,\n title,\n status: 'FAIL',\n passed: false,\n severity,\n message: `Failed to read ROLLBACK.md: ${e instanceof Error ? e.message : String(e)}`,\n };\n }\n}\n\nexport async function validateLastGoodDeploy(ctx: ValidatorContext): Promise<ValidationResult> {\n const ruleId = ctx.rule?.id ?? 'deployment.last-good-deploy';\n const standardId = ctx.standard?.id ?? 'deployment-safety-and-rollback';\n const title = ctx.rule?.title ?? 'Last Good Deploy Mechanism';\n const severity = ctx.rule?.severity ?? 'high';\n\n const rollbackPath = path.join(ctx.workspaceDir, 'ROLLBACK.md');\n if (!existsSync(rollbackPath)) {\n return {\n ruleId,\n standardId,\n title,\n status: 'FAIL',\n passed: false,\n severity,\n message: 'Cannot verify Last Good Deploy procedure because ROLLBACK.md is missing.',\n remediation: 'Document your hosting platform and exact instant rollback steps in ROLLBACK.md.',\n };\n }\n\n const content = await fs.readFile(rollbackPath, 'utf8');\n const lower = content.toLowerCase();\n\n const hostingDetected =\n lower.includes('vercel') ||\n lower.includes('netlify') ||\n lower.includes('docker') ||\n lower.includes('cloudflare') ||\n lower.includes('aws') ||\n lower.includes('render') ||\n lower.includes('railway') ||\n lower.includes('fly.io') ||\n lower.includes('heroku') ||\n lower.includes('kubernetes') ||\n lower.includes('button 1') ||\n lower.includes('last good deploy');\n\n if (!hostingDetected) {\n return {\n ruleId,\n standardId,\n title,\n status: 'WARN',\n passed: false,\n severity: 'medium',\n message: 'ROLLBACK.md does not specify a recognized hosting platform rollback procedure.',\n evidence: { file: 'ROLLBACK.md' },\n remediation: 'Document the specific hosting rollback steps (e.g. Vercel Instant Rollback, Netlify Publish Deploy) in ROLLBACK.md.',\n };\n }\n\n return {\n ruleId,\n standardId,\n title,\n status: 'PASS',\n passed: true,\n severity,\n message: 'Hosting rollback mechanism is documented in ROLLBACK.md.',\n evidence: { file: 'ROLLBACK.md' },\n };\n}\n\nexport async function validateBackupFirst(ctx: ValidatorContext): Promise<ValidationResult> {\n const ruleId = ctx.rule?.id ?? 'deployment.backup-first';\n const standardId = ctx.standard?.id ?? 'deployment-safety-and-rollback';\n const title = ctx.rule?.title ?? 'Backup First Procedure';\n const severity = ctx.rule?.severity ?? 'high';\n\n // 1. Check package.json scripts first\n const pkgPath = path.join(ctx.workspaceDir, 'package.json');\n if (existsSync(pkgPath)) {\n try {\n const raw = await fs.readFile(pkgPath, 'utf8');\n const pkg = JSON.parse(raw);\n const scripts = pkg.scripts || {};\n for (const [key, val] of Object.entries(scripts)) {\n if (key.includes('backup') || key.includes('dump') || (typeof val === 'string' && val.includes('dump'))) {\n return {\n ruleId,\n standardId,\n title,\n status: 'PASS',\n passed: true,\n severity,\n message: `Automated database backup script detected in package.json: \"${key}\".`,\n evidence: { file: 'package.json', details: { script: key, command: val } },\n };\n }\n }\n } catch (_err) {\n void _err;\n }\n }\n\n const rollbackPath = path.join(ctx.workspaceDir, 'ROLLBACK.md');\n if (!existsSync(rollbackPath)) {\n return {\n ruleId,\n standardId,\n title,\n status: 'FAIL',\n passed: false,\n severity,\n message: 'Database backup procedure is not documented (ROLLBACK.md missing).',\n remediation: 'Add a Backup First section to ROLLBACK.md with the exact dump command and test restore procedure.',\n };\n }\n\n const content = await fs.readFile(rollbackPath, 'utf8');\n const hasBackupCommand =\n content.includes('dump') ||\n content.includes('pg_dump') ||\n content.includes('supabase db dump') ||\n content.includes('mongodump') ||\n content.includes('sqlite3') ||\n content.includes('mysqldump');\n\n if (!hasBackupCommand) {\n return {\n ruleId,\n standardId,\n title,\n status: 'WARN',\n passed: false,\n severity: 'high',\n message: 'ROLLBACK.md mentions backups but lacks a concrete dump command (e.g. supabase db dump, pg_dump).',\n evidence: { file: 'ROLLBACK.md' },\n remediation: 'Include the exact runnable backup command in step 1 of your deploy checklist in ROLLBACK.md.',\n };\n }\n\n return {\n ruleId,\n standardId,\n title,\n status: 'PASS',\n passed: true,\n severity,\n message: 'Database backup procedure and runnable command are verified in ROLLBACK.md.',\n evidence: { file: 'ROLLBACK.md' },\n };\n}\n\nexport async function validateFeatureFlags(ctx: ValidatorContext): Promise<ValidationResult> {\n const ruleId = ctx.rule?.id ?? 'deployment.feature-flags';\n const standardId = ctx.standard?.id ?? 'deployment-safety-and-rollback';\n const title = ctx.rule?.title ?? 'Feature Flag Kill-Switch Capability';\n const severity = ctx.rule?.severity ?? 'high';\n\n const candidateFiles = [\n 'prisma/schema.prisma',\n 'backend/prisma/schema.prisma',\n 'src/config/features.ts',\n 'backend/src/config/features.ts',\n 'src/flags/features.ts',\n 'src/feature-flags.ts',\n 'src/features.ts',\n 'ROLLBACK.md',\n ];\n\n let found = false;\n let matchingFile: string | undefined;\n\n for (const rel of candidateFiles) {\n const full = path.join(ctx.workspaceDir, rel);\n if (existsSync(full)) {\n try {\n const text = await fs.readFile(full, 'utf8');\n if (text.includes('feature_flags') || text.includes('featureFlags') || text.includes('FeatureFlag')) {\n found = true;\n matchingFile = rel;\n break;\n }\n } catch (_err) {\n void _err;\n }\n }\n }\n\n // Also check recursively under src/ if not found\n if (!found) {\n const checkDir = async (dir: string, depth = 0): Promise<void> => {\n if (depth > 3 || found) return;\n if (!existsSync(dir)) return;\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (found) break;\n const p = path.join(dir, e.name);\n if (e.isDirectory() && !['node_modules', '.git', 'dist'].includes(e.name)) {\n await checkDir(p, depth + 1);\n } else if (e.isFile() && (e.name.includes('flag') || e.name.includes('feature'))) {\n const text = await fs.readFile(p, 'utf8');\n if (text.includes('featureFlags') || text.includes('feature_flags') || text.includes('FeatureFlag')) {\n found = true;\n matchingFile = path.relative(ctx.workspaceDir, p).replace(/\\\\/g, '/');\n break;\n }\n }\n }\n } catch (_err) {\n void _err;\n }\n };\n await checkDir(path.join(ctx.workspaceDir, 'src'));\n }\n\n if (!found) {\n return {\n ruleId,\n standardId,\n title,\n status: 'WARN',\n passed: false,\n severity: 'medium',\n message: 'No feature flag table or configuration switch (e.g. feature_flags) detected in schema or code.',\n remediation:\n 'Implement an on/off feature switch (Button 3 of the Undo Kit) so new capabilities can be disabled instantly without redeploying.',\n };\n }\n\n return {\n ruleId,\n standardId,\n title,\n status: 'PASS',\n passed: true,\n severity,\n message: `Feature switch capability detected in ${matchingFile}.`,\n evidence: { file: matchingFile },\n };\n}\n\nexport async function validateRecoveryRehearsal(ctx: ValidatorContext): Promise<ValidationResult> {\n const ruleId = ctx.rule?.id ?? 'deployment.recovery-rehearsal';\n const standardId = ctx.standard?.id ?? 'deployment-safety-and-rollback';\n const title = ctx.rule?.title ?? 'Documented Recovery Rehearsal';\n const severity = ctx.rule?.severity ?? 'high';\n\n const rollbackPath = path.join(ctx.workspaceDir, 'ROLLBACK.md');\n if (!existsSync(rollbackPath)) {\n return {\n ruleId,\n standardId,\n title,\n status: 'SKIPPED',\n passed: false,\n severity,\n message: 'Cannot verify recovery rehearsal because ROLLBACK.md is missing.',\n };\n }\n\n const content = await fs.readFile(rollbackPath, 'utf8');\n const lower = content.toLowerCase();\n\n const hasRehearsalEvidence =\n lower.includes('rehearsal log') &&\n (lower.includes('pass') || lower.includes('staging') || lower.includes('202') || lower.includes('drill'));\n\n if (!hasRehearsalEvidence) {\n return {\n ruleId,\n standardId,\n title,\n status: 'WARN',\n passed: false,\n severity: 'medium',\n message: 'No recorded recovery rehearsal entries found in ROLLBACK.md.',\n evidence: { file: 'ROLLBACK.md' },\n remediation:\n 'Practice the 4 undo buttons on a quiet day: roll back once, restore once, flip the switch once, and record times in ROLLBACK.md.',\n };\n }\n\n return {\n ruleId,\n standardId,\n title,\n status: 'PASS',\n passed: true,\n severity,\n message: 'Recovery rehearsal log verified in ROLLBACK.md.',\n evidence: { file: 'ROLLBACK.md' },\n };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"routing.js","sourceRoot":"","sources":["../../src/tasks/routing.ts"],"names":[],"mappings":"AAiBA,uHAAuH;AACvH,MAAM,CAAC,MAAM,SAAS,GAAmC;IACvD,QAAQ,EAAE;QACR,IAAI,EAAE,UAAU;QAChB,YAAY,EAAE,CAAC;QACf,QAAQ,EAAE,IAAI;QACd,SAAS,EAAE,KAAK;QAChB,KAAK,EAAE;YACL,+FAA+F;YAC/F,4FA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AAI,MAAM,KAAK,OAAO,CAAC,CAAC,YAAY,MAAM,CAAC,CAAC,YAAY,IAAI,CAAC;IAC7E,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,gDAAgD,EAAE,2BAA2B,EAAE,GAAG,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7G,CAAC","sourcesContent":["import type { TaskType } from './task.js';\n\nexport type Constraint = 'no-modify' | 'plan-only' | 'no-commit' | 'no-e2e' | 'no-tests' | 'no-fix';\n\nexport interface WorkflowSpec {\n type: TaskType;\n /** Highest context level normally needed (1 instructions … 6 tests/implementation). */\n contextDepth: 1 | 2 | 3 | 4 | 5 | 6;\n readOnly: boolean;\n trackTask: boolean;\n steps: string[];\n verification: string;\n agentSkills: string[];\n ponytail: string;\n knowledgeUpdate: string;\n}\n\n/** Single source of truth for routing. The generated Claude skill and docs/routing.md are rendered from this table. */\nexport const WORKFLOWS: Record<TaskType, WorkflowSpec> = {\n QUESTION: {\n type: 'QUESTION',\n contextDepth: 5,\n readOnly: true,\n trackTask: false,\n steps: [\n 'Read .devworkspace/context facts relevant to the topic (devworkspace context --topic <area>).',\n 'Use Graphify (if ready) or targeted search to locate the code; read only the files needed.',\n 'Answer with file references. State uncertainty explicitly.',\n ],\n verification: 'None. Do not modify files or run tests.',\n agentSkills: [],\n ponytail: 'Not used.',\n knowledgeUpdate: 'Only if you discovered a durable fact that is missing; record it with \"devworkspace fact add\".',\n },\n BUG: {\n type: 'BUG',\n contextDepth: 6,\n readOnly: false,\n trackTask: true,\n steps: [\n 'Check git status; protect uncommitted user changes.',\n 'Investigate and reproduce where practical.',\n 'Write a regression test and confirm it fails.',\n 'Fix the cause, confirm the test passes.',\n 'Run the applicable regression suite, then typecheck/lint/build as required by the testing contract.',\n 'Review the diff; record results with \"devworkspace task verify\".',\n ],\n verification: 'Regression test, applicable suite, typecheck, lint, build (whatever the testing contract marks required).',\n agentSkills: ['/test', '/review'],\n ponytail: 'Light review of the diff when review level is not \"off\".',\n knowledgeUpdate: 'Only if the bug revealed a persistent constraint or convention.',\n },\n FEATURE: {\n type: 'FEATURE',\n contextDepth: 6,\n readOnly: false,\n trackTask: true,\n steps: [\n 'Check git status. Read relevant facts and decisions.',\n 'Write acceptance criteria and a short plan (task update).',\n 'Write tests for the criteria, then implement.',\n 'Run targeted tests, then regression, then typecheck/lint/build.',\n 'Review the diff.',\n 'Update project knowledge for architecture, conventions or decisions that changed.',\n ],\n verification: 'Targeted tests, regression, typecheck, lint, build, review.',\n agentSkills: ['/spec', '/plan', '/build', '/test', '/review'],\n ponytail: 'Review for unnecessary complexity before completion.',\n knowledgeUpdate: 'Yes when the feature adds a module, integration, business rule or decision.',\n },\n REFACTOR: {\n type: 'REFACTOR',\n contextDepth: 6,\n readOnly: false,\n trackTask: true,\n steps: [\n 'Check git status. Analyse architecture, decisions and dependents (Graphify).',\n 'Record a baseline test result (devworkspace task tests --phase baseline).',\n 'Plan, then refactor in small verified steps.',\n 'Run targeted verification and the full regression suite; compare against the baseline.',\n 'Review the diff.',\n ],\n verification: 'Baseline vs after (no regressions), typecheck, lint, build, review.',\n agentSkills: ['/plan', '/code-simplify', '/review'],\n ponytail: 'Use for simplification review.',\n knowledgeUpdate: 'Yes if structure or conventions changed.',\n },\n DOCUMENTATION: {\n type: 'DOCUMENTATION',\n contextDepth: 4,\n readOnly: false,\n trackTask: false,\n steps: ['Read the code or facts being documented.', 'Edit documentation only.', 'Run documentation checks if the project has them (link or lint checks).'],\n verification: 'Only checks that apply to documentation.',\n agentSkills: [],\n ponytail: 'Not used.',\n knowledgeUpdate: 'Rarely.',\n },\n TESTING: {\n type: 'TESTING',\n contextDepth: 6,\n readOnly: false,\n trackTask: true,\n steps: ['Check git status.', 'Find existing test conventions.', 'Add tests; confirm they fail for the right reason where applicable.', 'Run the affected suite plus typecheck and lint.'],\n verification: 'Affected tests, typecheck, lint.',\n agentSkills: ['/test'],\n ponytail: 'Optional.',\n knowledgeUpdate: 'If the testing strategy or commands changed.',\n },\n PERFORMANCE: {\n type: 'PERFORMANCE',\n contextDepth: 6,\n readOnly: false,\n trackTask: true,\n steps: ['Measure first; record the baseline.', 'Change one thing at a time.', 'Re-measure and run the regression suite and build.', 'Review.'],\n verification: 'Before/after measurement, regression suite, build.',\n agentSkills: ['/webperf', '/review'],\n ponytail: 'Review for added complexity.',\n knowledgeUpdate: 'If a persistent constraint or decision emerged.',\n },\n SECURITY: {\n type: 'SECURITY',\n contextDepth: 6,\n readOnly: false,\n trackTask: true,\n steps: ['Check git status.', 'Understand the threat and the affected paths.', 'Test that demonstrates the issue, then fix.', 'Regression suite, typecheck, lint, build.', 'Security-focused review. Never print secret values.'],\n verification: 'Regression and exploit test, typecheck, lint, build, review.',\n agentSkills: ['/test', '/review'],\n ponytail: 'Use for bug and security review of the diff.',\n knowledgeUpdate: 'Yes for new security conventions or decisions.',\n },\n ARCHITECTURE: {\n type: 'ARCHITECTURE',\n contextDepth: 6,\n readOnly: false,\n trackTask: true,\n steps: ['Read facts, decisions and architecture notes; map structure with Graphify.', 'Present options and record the chosen one with \"devworkspace decision add\".', 'Plan and implement in verified steps.', 'Full verification and review.'],\n verification: 'Baseline vs after, typecheck, lint, build, review.',\n agentSkills: ['/spec', '/plan', '/build', '/review'],\n ponytail: 'Review for unnecessary abstraction.',\n knowledgeUpdate: 'Always: architecture notes and the decision record.',\n },\n RELEASE: {\n type: 'RELEASE',\n contextDepth: 6,\n readOnly: false,\n trackTask: true,\n steps: ['Check git status and branch.', 'Run the full testing contract including integration/e2e where available.', 'Update changelog and version per project convention.', 'Do not publish or push without explicit user authorisation.'],\n verification: 'Everything in the testing contract.',\n agentSkills: ['/ship'],\n ponytail: 'Optional final review.',\n knowledgeUpdate: 'If release process facts changed.',\n },\n MAINTENANCE: {\n type: 'MAINTENANCE',\n contextDepth: 4,\n readOnly: false,\n trackTask: true,\n steps: ['Check git status.', 'Make the change.', 'Run lint and build; run tests when behaviour could change.'],\n verification: 'Lint, build, tests if behaviour could change.',\n agentSkills: [],\n ponytail: 'Optional.',\n knowledgeUpdate: 'Only for changed commands or tooling.',\n },\n};\n\nconst OVERRIDE_PATTERNS: [Constraint, RegExp][] = [\n ['no-modify', /\\b(?:only|just)\\s+(?:explain|describe|investigate|look|read|review)\\b|\\b(?:do\\s*n[o']t|don'?t|never|without)\\s+(?:modify|modifying|change|changing|edit|editing|touch|touching)\\b|\\bread[- ]only\\b|\\bno\\s+changes\\b/i],\n ['plan-only', /\\b(?:only|just)\\s+(?:make\\s+|write\\s+|give\\s+me\\s+)?a\\s+plan\\b|\\bplan\\s+only\\b|\\bwithout\\s+implementing(?:\\s+it)?\\b/i],\n ['no-commit', /\\b(?:do\\s*n[o']t|don'?t|never)\\s+commit\\b|\\bno\\s+commits?\\b/i],\n ['no-e2e', /\\b(?:do\\s*n[o']t|don'?t|skip|no)\\s+(?:run\\s+)?(?:the\\s+)?(?:e2e|end[- ]to[- ]end)\\b/i],\n ['no-tests', /\\b(?:do\\s*n[o']t|don'?t|skip)\\s+(?:run\\s+)?(?:any\\s+|the\\s+)?tests\\b(?!\\s+but)/i],\n ['no-fix', /\\b(?:do\\s*n[o']t|don'?t|never)\\s+fix\\b|\\bwithout\\s+fixing\\b|\\bno[- ]fix\\b/i],\n];\n\nexport function detectConstraints(text: string): Constraint[] {\n const str = typeof text === 'string' ? text : '';\n return OVERRIDE_PATTERNS.filter(([, re]) => re.test(str)).map(([c]) => c);\n}\n\nexport interface Classification {\n type: TaskType;\n confidence: 'high' | 'low';\n constraints: Constraint[];\n /** True when the request must not change files (question type, or an explicit user override). */\n readOnly: boolean;\n}\n\nconst QUESTION_START = /^\\s*(?:where|what|which|who|when|how\\s+(?:does|do|is|are|can|should)|why|explain|describe|show\\s+me|walk\\s+me|is\\s+there|are\\s+there|can\\s+you\\s+(?:explain|tell|show)|tell\\s+me|list|find|trace|follow|inspect)\\b/i;\nconst EXPLORATION_START = /^\\s*(?:investigate|examine|explore|audit)\\b/i;\nconst IMPERATIVE_START =\n /^\\s*(?:fix|add|implement|create|build|refactor|remove|delete|update|change|rename|write|make|migrate|upgrade|optimi[sz]e|release|publish|validate|ensure|prevent|enforce|guard|reject|restrict|handle|resolve|patch|repair|address|correct|replace|move|extract|rewrite|convert|improve|enable|disable|support|introduce|apply|configure|install|harden|secure|scope|isolate|architect|design)\\b/i;\n/** A direct yes/no or open question: it ends in a question mark and does not start like an instruction. */\nconst DIRECT_QUESTION = /\\?\\s*$/;\n/** Action-oriented release phrases where releasing is the primary engineering intent. */\nconst ACTIVE_RELEASE = /\\b(?:prepare\\s+release|cut\\s+release|ready\\s+release)\\b|\\b(?:release|publish|deploy|ship)\\s+(?:the\\s+)?(?:package|project|build|app|version|v\\d+)\\b|^\\s*(?:release|publish|deploy|ship)\\b|\\brelease\\s+(?:version\\s+)?v?\\d+/i;\n\n/** Heuristic classifier used to propose a task type. The agent may override it; ambiguous input defaults to the safest (read-only) type. */\nexport function classifyRequest(text: string): Classification {\n const str = typeof text === 'string' ? text : '';\n const constraints = detectConstraints(str);\n // Negated phrases (\"don't fix anything\") describe limits, not the task itself.\n const t = OVERRIDE_PATTERNS.reduce((acc, [, re]) => acc.replace(new RegExp(re.source, re.flags + 'g'), ' '), str).trim();\n const make = (type: TaskType, confidence: 'high' | 'low'): Classification => ({\n type,\n confidence,\n constraints,\n readOnly: WORKFLOWS[type].readOnly || constraints.includes('no-modify') || constraints.includes('plan-only') || constraints.includes('no-fix'),\n });\n if ((QUESTION_START.test(t) || DIRECT_QUESTION.test(t)) && !IMPERATIVE_START.test(t)) return make('QUESTION', 'high');\n if (/\\b(?:add|write|improve|increase)\\s+(?:\\w+\\s+)?(?:unit\\s+|e2e\\s+|integration\\s+|regression\\s+|smoke\\s+)?tests?\\b|\\btest coverage\\b|^\\s*run\\s+(?:the\\s+|all\\s+)?(?:\\w+\\s+)?tests?\\b|\\b(?:mock|stub|fixture|fake|harness)\\w*(?:\\s+\\w+)?\\s+for\\s+(?:\\w+\\s+)*tests?\\b/i.test(t)) return make('TESTING', 'high');\n if (/\\b(?:upgrade|bump|update\\s+(?:\\w+\\s+)?dependenc\\w*)\\b/i.test(t)) return make('MAINTENANCE', 'high');\n if (/\\b(?:vulnerab\\w*|csrf|xss|sql injection|cve-\\d+|cross-?tenant|tenant isolation|privilege escalation|idor)\\b/i.test(t)) return make('SECURITY', 'high');\n if (/\\b(?:fix|bug|broken|crash(?:es|ing)?|regression|not working|fails?|failing|exception|error|memory\\s+leak|resource\\s+leak|leak(?:s|ing)?|deadlock|infinite\\s+loop)\\b/i.test(t)) return make('BUG', 'high');\n if (/\\b(?:refactor|restructure|reorgani[sz]e|clean\\s?up|simplify|de-?duplicate)\\b/i.test(t)) return make('REFACTOR', 'high');\n if (/\\b(?:vulnerab\\w*|security|csrf|xss|sql injection|sanitiz\\w*|harden\\w*|cve-\\d+|cross-?tenant|tenant isolation|ownership|authori[sz]ation|privilege escalation|idor)\\b/i.test(t)) return make('SECURITY', 'high');\n if (/\\b(?:performance|slow|latency|speed up|optimi[sz]e|throughput)\\b/i.test(t)) return make('PERFORMANCE', 'high');\n if (ACTIVE_RELEASE.test(t)) return make('RELEASE', 'high');\n if (/\\b(?:document\\w*|readme|docs?|changelog|jsdoc|docstring|guide)\\b/i.test(t)) return make('DOCUMENTATION', 'high');\n if (/\\b(?:release|publish|deploy|ship|version bump)\\b/i.test(t)) return make('RELEASE', 'high');\n if (/\\b(?:upgrade|bump|update\\s+dependenc\\w*|chore|lint(?:ing)?|format(?:ting)?)\\b/i.test(t)) return make('MAINTENANCE', 'high');\n if (/\\b(?:redesign|(?:re-?)?architect\\w*|migrate\\s+to|architecture)\\b/i.test(t)) return make('ARCHITECTURE', 'high');\n if (/\\b(?:add|implement|create|build|support|introduce|enable|new)\\b/i.test(t)) return make('FEATURE', 'high');\n if (EXPLORATION_START.test(t)) return make('QUESTION', 'high');\n // An instruction we cannot place is still a request to change something. Never default it to a read-only question.\n if (IMPERATIVE_START.test(t)) return make('FEATURE', 'low');\n return make('QUESTION', 'low');\n}\n\nexport function renderRoutingTable(): string {\n const rows = (Object.values(WORKFLOWS) as WorkflowSpec[]).map((w) => {\n const flags = [w.readOnly ? 'read-only' : 'modifies code', w.trackTask ? 'tracked task' : 'no task file'].join(', ');\n return `| ${w.type} | ${flags} | L${w.contextDepth} | ${w.verification} |`;\n });\n return ['| Type | Nature | Max context | Verification |', '| --- | --- | --- | --- |', ...rows].join('\\n');\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"task.js","sourceRoot":"","sources":["../../src/tasks/task.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAqB,MAAM,sBAAsB,CAAC;AACzE,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,sBAAsB,EAAW,MAAM,sBAAsB,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAEvD,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,UAAU;IACV,KAAK;IACL,SAAS;IACT,UAAU;IACV,eAAe;IACf,SAAS;IACT,aAAa;IACb,UAAU;IACV,cAAc;IACd,SAAS;IACT,aAAa;CACL,CAAC;AAGX,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,MAAM,EAAE,WAAW,EAAE,SAAS,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,CAAU,CAAC;AAG7I,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,SAAS,EAAE,MAAM,EAAE,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,SAAS,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC;IAC7D,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AAC5B,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { DevWorkspaceError } from '../errors/index.js';\nimport { Check } from '../config/validate.js';\nimport { SCHEMA_VERSION, type CommandEntry } from '../config/schemas.js';\nimport { atomicWriteJson, ensureDir, pathExists, randomId } from '../utils/fs.js';\nimport { readVersioned } from '../core/versioned.js';\nimport { backupIfVersionChanges, type Ws } from '../core/workspace.js';\nimport { containsSecret } from '../security/redact.js';\n\nexport const TASK_TYPES = [\n 'QUESTION',\n 'BUG',\n 'FEATURE',\n 'REFACTOR',\n 'DOCUMENTATION',\n 'TESTING',\n 'PERFORMANCE',\n 'SECURITY',\n 'ARCHITECTURE',\n 'RELEASE',\n 'MAINTENANCE',\n] as const;\nexport type TaskType = (typeof TASK_TYPES)[number];\n\nexport const TASK_STATUSES = ['IDEA', 'SPECIFIED', 'PLANNED', 'IN_PROGRESS', 'TESTING', 'REVIEW', 'BLOCKED', 'FAILED', 'COMPLETED'] as const;\nexport type TaskStatus = (typeof TASK_STATUSES)[number];\n\nexport const VERIFY_STATUSES = ['PENDING', 'PASS', 'FAIL', 'SKIPPED', 'COULD_NOT_RUN'] as const;\nexport type VerifyStatus = (typeof VERIFY_STATUSES)[number];\n\n/**\n * One recorded result for one package. `executed` means DevWorkspace ran the contract command itself and saw the exit\n * code; `claimed` is somebody's report (agent or person) that DevWorkspace could not observe.\n */\nexport interface Evidence {\n kind: 'executed' | 'claimed';\n at: string;\n /** Package directory relative to the project root; \".\" for the root. */\n package: string;\n command?: string;\n exitCode?: number | null;\n durationMs?: number;\n /** Fingerprint of the task's changes inside this package when the result was recorded. */\n scope?: string;\n /** A claim the user explicitly vouched for (--reason user-override). */\n userOverride?: boolean;\n /** One-line, scrubbed explanation (failure tail or refusal reason). Never a connection string or credential. */\n note?: string;\n}\n\nexport interface VerificationItem {\n check: string;\n required: boolean;\n status: VerifyStatus;\n reason?: string;\n detail?: string;\n updatedAt?: string;\n /** Latest result per package. Absent on tasks recorded by older versions. */\n evidence?: Evidence[];\n}\n\n/** Files that were already modified when the task was created, so they are not blamed on the task. */\nexport interface TaskScope {\n capturedAt: string;\n /** Git HEAD when the task was created; null outside a repository. */\n head: string | null;\n /** Project-relative path -> content hash of files already modified at creation (\"deleted\" for removed files). */\n baseline: Record<string, string>;\n}\n\nexport interface TestCounts {\n passed: number;\n failed: number;\n}\n\nexport interface Attestations {\n userWorkIntact: boolean;\n knowledgeReviewed: boolean;\n finalStateInspected: boolean;\n}\n\nexport interface Task {\n schemaVersion: number;\n id: string;\n title: string;\n type: TaskType;\n status: TaskStatus;\n createdAt: string;\n updatedAt: string;\n description: string;\n acceptanceCriteria: string[];\n plan: string[];\n affectedAreas: string[];\n verification: VerificationItem[];\n tests: { baseline?: TestCounts; after?: TestCounts };\n attestations: Attestations;\n /** Present on tasks created by 0.2.2+: enables package-aware, evidence-based completion. */\n scope?: TaskScope;\n decisions: string[];\n blockers: string[];\n constraints: string[];\n completionSummary?: string;\n history: { at: string; from: TaskStatus | null; to: TaskStatus; note?: string }[];\n}\n\nconst TRANSITIONS: Record<TaskStatus, TaskStatus[]> = {\n IDEA: ['SPECIFIED', 'PLANNED', 'IN_PROGRESS', 'BLOCKED', 'FAILED'],\n SPECIFIED: ['PLANNED', 'IN_PROGRESS', 'BLOCKED', 'IDEA'],\n PLANNED: ['IN_PROGRESS', 'SPECIFIED', 'BLOCKED', 'IDEA'],\n IN_PROGRESS: ['TESTING', 'REVIEW', 'COMPLETED', 'BLOCKED', 'FAILED', 'PLANNED'],\n TESTING: ['IN_PROGRESS', 'REVIEW', 'COMPLETED', 'BLOCKED', 'FAILED'],\n REVIEW: ['IN_PROGRESS', 'TESTING', 'COMPLETED', 'BLOCKED', 'FAILED'],\n BLOCKED: ['IN_PROGRESS', 'PLANNED', 'SPECIFIED', 'IDEA', 'FAILED'],\n FAILED: ['IN_PROGRESS', 'IDEA'],\n COMPLETED: ['IN_PROGRESS'],\n};\n\nexport function allowedTransitions(from: TaskStatus): TaskStatus[] {\n return TRANSITIONS[from];\n}\n\nconst CODE_CHANGING: TaskType[] = ['BUG', 'FEATURE', 'REFACTOR', 'PERFORMANCE', 'SECURITY', 'ARCHITECTURE', 'MAINTENANCE', 'TESTING', 'RELEASE'];\n\nconst CHECKS_BY_TYPE: Record<TaskType, string[]> = {\n QUESTION: [],\n DOCUMENTATION: [],\n BUG: ['unit', 'typecheck', 'lint', 'build'],\n FEATURE: ['unit', 'typecheck', 'lint', 'build', 'review'],\n REFACTOR: ['unit', 'typecheck', 'lint', 'build', 'review'],\n TESTING: ['unit', 'typecheck', 'lint'],\n PERFORMANCE: ['unit', 'build', 'review'],\n SECURITY: ['unit', 'typecheck', 'lint', 'build', 'review'],\n ARCHITECTURE: ['unit', 'typecheck', 'lint', 'build', 'review'],\n RELEASE: ['unit', 'typecheck', 'lint', 'build', 'integration', 'e2e'],\n MAINTENANCE: ['lint', 'build'],\n};\n\nexport function isCodeChanging(type: TaskType): boolean {\n return CODE_CHANGING.includes(type);\n}\n\n/** Verification a task of this type needs, given what the project actually offers. Unavailable checks are never demanded. */\nexport function requiredChecksFor(type: TaskType, contract: CommandEntry[], reviewLevel: 'off' | 'light' | 'strict' = 'light'): VerificationItem[] {\n const available = new Set(contract.filter((c) => c.available).map((c) => c.id as string));\n const items: VerificationItem[] = [];\n for (const check of CHECKS_BY_TYPE[type]) {\n if (check === 'review') {\n if (reviewLevel === 'off') continue;\n } else if (!available.has(check)) continue;\n items.push({ check, required: true, status: 'PENDING' });\n }\n return items;\n}\n\nexport function newTaskId(now: Date = new Date()): string {\n const d = now.toISOString().slice(0, 10).replace(/-/g, '');\n return `T-${d}-${randomId(2)}`;\n}\n\nexport interface NewTaskInput {\n title: string;\n type: TaskType;\n description?: string;\n verification: VerificationItem[];\n constraints?: string[];\n}\n\nexport function createTaskObject(input: NewTaskInput, now: string, id = newTaskId()): Task {\n const title = input.title.trim().slice(0, 200);\n if (!title) throw new DevWorkspaceError('USAGE', 'Task title must not be empty.');\n const task: Task = {\n schemaVersion: SCHEMA_VERSION,\n id,\n title,\n type: input.type,\n status: 'IDEA',\n createdAt: now,\n updatedAt: now,\n description: (input.description ?? '').trim().slice(0, 4000),\n acceptanceCriteria: [],\n plan: [],\n affectedAreas: [],\n verification: input.verification,\n tests: {},\n attestations: { userWorkIntact: false, knowledgeReviewed: false, finalStateInspected: false },\n decisions: [],\n blockers: [],\n constraints: input.constraints ?? [],\n history: [{ at: now, from: null, to: 'IDEA' }],\n };\n assertNoSecrets(task);\n return task;\n}\n\nexport function assertNoSecrets(task: Task): void {\n if (containsSecret(JSON.stringify(task))) {\n throw new DevWorkspaceError('SECURITY', 'Task content looks like it contains a secret; refusing to store it.', {\n hint: 'Remove credential values from titles, plans and notes.',\n });\n }\n}\n\nexport function validateTask(v: unknown, file = 'task'): Task {\n const c = new Check(file);\n const o = c.obj(v);\n c.at_('schemaVersion').int(o.schemaVersion, 1);\n c.at_('id').str(o.id, { min: 3, max: 64 });\n c.at_('title').str(o.title, { min: 1, max: 300 });\n c.at_('type').oneOf(o.type, TASK_TYPES);\n c.at_('status').oneOf(o.status, TASK_STATUSES);\n c.at_('createdAt').iso(o.createdAt);\n c.at_('updatedAt').iso(o.updatedAt);\n for (const k of ['acceptanceCriteria', 'plan', 'affectedAreas', 'decisions', 'blockers', 'constraints'] as const) c.at_(k).strArr(o[k]);\n c.at_('verification')\n .arr(o.verification, 100)\n .forEach((item, i) => {\n const ic = c.at_(`verification.${i}`);\n const io = ic.obj(item);\n ic.at_('check').str(io.check, { max: 50 });\n ic.at_('required').bool(io.required);\n ic.at_('status').oneOf(io.status, VERIFY_STATUSES);\n if (io.evidence !== undefined) {\n ic.at_('evidence')\n .arr(io.evidence, 100)\n .forEach((e, j) => {\n const ec = c.at_(`verification.${i}.evidence.${j}`);\n const eo = ec.obj(e);\n ec.at_('kind').oneOf(eo.kind, ['executed', 'claimed'] as const);\n ec.at_('package').str(eo.package, { max: 240 });\n });\n }\n });\n if (o.scope !== undefined) {\n const sc = c.at_('scope').obj(o.scope);\n c.at_('scope.capturedAt').iso(sc.capturedAt);\n c.at_('scope.baseline').obj(sc.baseline);\n }\n const a = c.at_('attestations').obj(o.attestations);\n c.at_('attestations.userWorkIntact').bool(a.userWorkIntact);\n c.at_('attestations.knowledgeReviewed').bool(a.knowledgeReviewed);\n c.at_('attestations.finalStateInspected').bool(a.finalStateInspected);\n c.at_('tests').obj(o.tests);\n c.at_('history').arr(o.history, 500);\n return o as unknown as Task;\n}\n\nexport interface GateResult {\n ok: boolean;\n failures: string[];\n warnings: string[];\n}\n\n/** What the gate needs to know beyond the task itself: the contract and what the task changed, per package. */\nexport interface GateContext {\n contract: CommandEntry[];\n /**\n * Fingerprint of the task's changes inside each package (\".\" = everything). `null` means the changes could not be\n * determined (not a Git repository, or nothing changed since the task started), so every package counts as affected.\n */\n scope: Record<string, string> | null;\n}\n\nconst UNKNOWN_SCOPE = 'unknown';\n\n/** Per-package requirements of one check. Returns false when the contract has no applicable package entry. */\nfunction packageGate(v: VerificationItem, ctx: GateContext, failures: string[], warnings: string[]): boolean {\n const entries = ctx.contract.filter((c) => c.id === v.check && c.available && !c.mutates);\n if (entries.length === 0) return false;\n const known = ctx.scope !== null;\n const unknown = !known;\n let applicable = 0;\n for (const entry of entries) {\n const pkg = entry.cwd ?? '.';\n const fp = known ? ctx.scope![pkg] : UNKNOWN_SCOPE;\n if (fp === undefined) continue; // this package was not changed, so this check does not apply to it\n applicable++;\n const label = `${v.check} [${pkg}]`;\n const ev = v.evidence?.find((e) => e.package === pkg);\n if (!ev) failures.push(`${label}: not run for the current changes`);\n else if (ev.kind === 'claimed' && !ev.userOverride) failures.push(`${label}: only claimed, not executed (run: devworkspace task run <id> ${v.check} --package ${pkg})`);\n else if (ev.kind === 'claimed') warnings.push(`${label}: accepted on the user's word; DevWorkspace did not observe it run`);\n else if (ev.exitCode !== 0) failures.push(`${label}: FAIL (exit ${ev.exitCode ?? 'none'})`);\n else if (!unknown && ev.scope !== fp) failures.push(`${label}: passed, but files changed afterwards; run it again`);\n }\n if (known && applicable === 0) warnings.push(`${v.check}: no package with this check was changed`);\n return true;\n}\n\n/**\n * The completion gate. A task is only COMPLETED when every applicable requirement holds.\n * Tasks that carry a `scope` (created by 0.2.2+) are checked per changed package against executed evidence; older\n * tasks keep the original rules.\n */\nexport function evaluateGate(task: Task, ctx?: GateContext): GateResult {\n const failures: string[] = [];\n const warnings: string[] = [];\n const scoped = !!ctx && !!task.scope;\n for (const v of task.verification) {\n if (!v.required) continue;\n if (v.status === 'FAIL') failures.push(`${v.check}: FAIL`);\n else if (v.status === 'COULD_NOT_RUN') failures.push(`${v.check}: could not run${v.detail ? ` (${v.detail})` : ''}`);\n else if (v.status === 'SKIPPED') {\n if (v.reason === 'user-override') warnings.push(`${v.check}: skipped at the user's request; completion is less certain`);\n else failures.push(`${v.check}: skipped without a user override`);\n } else if (scoped && packageGate(v, ctx!, failures, warnings)) {\n // handled per package\n } else if (v.status === 'PENDING') failures.push(`${v.check}: not run yet`);\n }\n const { baseline, after } = task.tests;\n if (baseline && !after) failures.push('baseline test results recorded, but no results after the change');\n if (baseline && after) {\n if (after.failed > baseline.failed) failures.push(`regression: failures rose from ${baseline.failed} to ${after.failed}`);\n if (after.passed < baseline.passed) failures.push(`regression: passing tests fell from ${baseline.passed} to ${after.passed}`);\n }\n const isReadOnly = task.constraints?.some((c) => c === 'no-modify' || c === 'no-fix' || c === 'plan-only');\n if (isReadOnly && ctx?.scope && Object.keys(ctx.scope).length > 0) {\n failures.push('files were modified despite read-only constraint (no-modify, no-fix, or plan-only)');\n }\n if (isCodeChanging(task.type) && !isReadOnly) {\n if (!task.attestations.userWorkIntact) failures.push('not confirmed: no user work was overwritten');\n if (!task.attestations.knowledgeReviewed) failures.push('not confirmed: project knowledge was reviewed for updates');\n if (!task.attestations.finalStateInspected) failures.push('not confirmed: final repository state was inspected');\n }\n if ((isCodeChanging(task.type) || task.type === 'DOCUMENTATION' || isReadOnly) && !(task.completionSummary ?? '').trim()) {\n failures.push('completion summary is missing');\n }\n return { ok: failures.length === 0, failures, warnings };\n}\n\nexport function transitionTask(task: Task, to: TaskStatus, now: string, note?: string, ctx?: GateContext): GateResult | null {\n if (task.status === to) return null;\n if (!TRANSITIONS[task.status].includes(to)) {\n throw new DevWorkspaceError('GATE', `Cannot move a task from ${task.status} to ${to}.`, {\n hint: `Allowed from ${task.status}: ${TRANSITIONS[task.status].join(', ')}.`,\n });\n }\n let gate: GateResult | null = null;\n if (to === 'COMPLETED') {\n gate = evaluateGate(task, ctx);\n if (!gate.ok) {\n throw new DevWorkspaceError('GATE', `Task ${task.id} cannot be completed:\\n - ${gate.failures.join('\\n - ')}`, {\n hint: 'Resolve the items above (or mark the task BLOCKED/FAILED). A task is never complete while verification is failing.',\n });\n }\n }\n task.history.push({ at: now, from: task.status, to, ...(note ? { note: note.slice(0, 300) } : {}) });\n task.status = to;\n task.updatedAt = now;\n return gate;\n}\n\nexport function nextRequiredStep(task: Task, ctx?: GateContext): string {\n switch (task.status) {\n case 'COMPLETED':\n return 'None. The task is complete.';\n case 'FAILED':\n return 'Review the failure, then move the task back to IN_PROGRESS or close the idea.';\n case 'BLOCKED':\n return task.blockers.length > 0 ? `Resolve blocker: ${task.blockers[task.blockers.length - 1]}` : 'Identify and record what blocks this task.';\n case 'IDEA':\n return 'Clarify acceptance criteria, then plan.';\n case 'SPECIFIED':\n return 'Write a plan.';\n case 'PLANNED':\n return 'Start implementation (baseline verification first for meaningful changes).';\n default: {\n const pending = task.verification.filter((v) => v.required && (v.status === 'PENDING' || v.status === 'FAIL' || v.status === 'COULD_NOT_RUN'));\n if (pending.length > 0) return `Run/fix verification: ${pending.map((p) => `${p.check} (${p.status.toLowerCase().replace(/_/g, ' ')})`).join(', ')}.`;\n const g = evaluateGate(task, ctx);\n return g.ok ? 'All gates pass. Mark the task COMPLETED.' : `Satisfy the completion gate: ${g.failures[0]}`;\n }\n }\n}\n\n// ---------- storage ----------\n\nfunction taskFile(ws: Ws, task: Pick<Task, 'id' | 'status'>): string {\n return path.join(task.status === 'COMPLETED' ? ws.tasksCompleted : ws.tasksActive, `${task.id}.json`);\n}\n\nexport async function saveTask(ws: Ws, task: Task): Promise<void> {\n validateTask(task);\n assertNoSecrets(task);\n const dest = taskFile(ws, task);\n await backupIfVersionChanges(ws, dest, task.schemaVersion);\n await ensureDir(path.dirname(dest));\n await atomicWriteJson(dest, task);\n const other = path.join(task.status === 'COMPLETED' ? ws.tasksActive : ws.tasksCompleted, `${task.id}.json`);\n await fs.rm(other, { force: true });\n}\n\nexport async function loadTask(ws: Ws, idOrPrefix: string): Promise<Task> {\n for (const dir of [ws.tasksActive, ws.tasksCompleted]) {\n if (!(await pathExists(dir))) continue;\n const names = (await fs.readdir(dir)).filter((n) => n.endsWith('.json'));\n const hits = names.filter((n) => n === `${idOrPrefix}.json` || n.startsWith(idOrPrefix));\n if (hits.length > 1) {\n const exact = hits.find((n) => n === `${idOrPrefix}.json`);\n if (!exact) throw new DevWorkspaceError('USAGE', `Task id \"${idOrPrefix}\" is ambiguous.`, { hint: 'Use more characters of the id.' });\n hits.splice(0, hits.length, exact);\n }\n if (hits.length === 1) {\n const file = path.join(dir, hits[0]!);\n return (await readVersioned(file, 'task', SCHEMA_VERSION, validateTask)).data;\n }\n }\n throw new DevWorkspaceError('NOT_FOUND', `No task matching \"${idOrPrefix}\".`, { hint: 'List tasks with \"devworkspace task list --all\".' });\n}\n\nexport interface TaskListing {\n tasks: Task[];\n corrupt: { file: string; error: string }[];\n}\n\nexport async function listTasks(ws: Ws, opts: { includeCompleted?: boolean } = {}): Promise<TaskListing> {\n const tasks: Task[] = [];\n const corrupt: { file: string; error: string }[] = [];\n const dirs = opts.includeCompleted ? [ws.tasksActive, ws.tasksCompleted] : [ws.tasksActive];\n for (const dir of dirs) {\n if (!(await pathExists(dir))) continue;\n for (const name of (await fs.readdir(dir)).filter((n) => n.endsWith('.json')).sort()) {\n try {\n tasks.push((await readVersioned(path.join(dir, name), 'task', SCHEMA_VERSION, validateTask)).data);\n } catch (e) {\n corrupt.push({ file: `${path.basename(dir)}/${name}`, error: (e as Error).message });\n }\n }\n }\n tasks.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n return { tasks, corrupt };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"cleanup.js","sourceRoot":"","sources":["../../src/utils/cleanup.ts"],"names":[],"mappings":"AAAA,MAAM,SAAS,GAAG,IAAI,GAAG,EAAc,CAAC;AAExC,gFAAgF;AAChF,MAAM,UAAU,SAAS,CAAC,EAAc;IACtC,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAClB,OAAO,GAAG,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,WAAW;IACzB,KAAK,MAAM,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,EAAE,CAAC;QAChC,IAAI,CAAC;YACH,EAAE,EAAE,CAAC;QACP,CAAC;QAAC,MAAM,CAAC;YACP,iBAAiB;QACnB,CAAC;IACH,CAAC;IACD,SAAS,CAAC,KAAK,EAAE,CAAC;AACpB,CAAC","sourcesContent":["const callbacks = new Set<() => void>();\n\n/** Register a synchronous cleanup (e.g. release a lock). Returns a disposer. */\nexport function onCleanup(fn: () => void): () => void {\n callbacks.add(fn);\n return () => callbacks.delete(fn);\n}\n\nexport function runCleanups(): void {\n for (const fn of [...callbacks]) {\n try {\n fn();\n } catch {\n /* best effort */\n }\n }\n callbacks.clear();\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"fs.js","sourceRoot":"","sources":["../../src/utils/fs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3D,OAAO,EAAE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IAAI,CAAC,CAAC,MAAM,EAAE;gBAAE,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IACD,MAAM,IAAI,CAAC,GAAG,CAAC,CAAC;IAChB,OAAO,GAAG,CAAC;AACb,CAAC;AAED,yGAAyG;AACzG,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,IAAY,EAAE,IAAY;IACjE,IAAI,CAAC;QACH,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,KAAK,IAAI;YAAE,OAAO,KAAK,CAAC;IAC/D,CAAC;IAAC,MAAM,CAAC;QACP,0BAA0B;IAC5B,CAAC;IACD,MAAM,eAAe,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,IAAY,EAAE,KAAc;IACnE,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,CAAC;IACnD,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACjB,OAAO,kBAAkB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { promises as fs, createReadStream } from 'node:fs';\nimport { createHash, randomBytes } from 'node:crypto';\nimport path from 'node:path';\nimport { DevWorkspaceError } from '../errors/index.js';\n\nexport const MAX_JSON_BYTES = 5 * 1024 * 1024;\n\nexport async function pathExists(p: string): Promise<boolean> {\n try {\n await fs.access(p);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function ensureDir(p: string): Promise<void> {\n await fs.mkdir(p, { recursive: true });\n}\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n let lastErr: unknown;\n // Windows briefly denies renames while another process (reader, indexer, editor file watcher) holds the target.\n for (let i = 0; i < 20; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (e) {\n lastErr = e;\n const code = (e as NodeJS.ErrnoException).code;\n if (code !== 'EPERM' && code !== 'EBUSY' && code !== 'EACCES') break;\n await new Promise((r) => setTimeout(r, Math.min(25 * (i + 1), 150)));\n }\n }\n throw lastErr;\n}\n\n/** Write to a temp file in the same directory, flush it, then atomically rename into place. */\nexport async function atomicWriteFile(file: string, data: string | Uint8Array, validate?: (data: string) => void): Promise<void> {\n await ensureDir(path.dirname(file));\n if (validate && typeof data === 'string') validate(data);\n const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;\n let fh;\n try {\n fh = await fs.open(tmp, 'wx');\n await fh.writeFile(data);\n await fh.sync();\n await fh.close();\n fh = undefined;\n await renameWithRetry(tmp, file);\n } catch (e) {\n if (fh) await fh.close().catch(() => undefined);\n await fs.rm(tmp, { force: true }).catch(() => undefined);\n throw new DevWorkspaceError('IO', `Could not write ${path.basename(file)}.`, {\n cause: e,\n hint: 'Check file permissions and free disk space.',\n });\n }\n}\n\nexport async function atomicWriteJson(file: string, value: unknown): Promise<void> {\n const text = JSON.stringify(value, null, 2) + '\\n';\n await atomicWriteFile(file, text, (t) => {\n JSON.parse(t);\n });\n}\n\nexport async function readJsonFile<T = unknown>(file: string, maxBytes = MAX_JSON_BYTES): Promise<T> {\n let stat;\n try {\n stat = await fs.stat(file);\n } catch (e) {\n throw new DevWorkspaceError('NOT_FOUND', `File not found: ${path.basename(file)}`, { cause: e });\n }\n if (stat.size > maxBytes) {\n throw new DevWorkspaceError('SCHEMA', `${path.basename(file)} is unreasonably large (${stat.size} bytes).`, {\n hint: 'Restore it from version control or a backup in .devworkspace/local/backups.',\n });\n }\n const text = await fs.readFile(file, 'utf8');\n try {\n return JSON.parse(text.replace(/^\\uFEFF/, '')) as T;\n } catch (e) {\n throw new DevWorkspaceError('SCHEMA', `${path.basename(file)} contains malformed JSON.`, {\n cause: e,\n hint: 'Restore the file from version control (git checkout -- <file>) or from .devworkspace/local/backups.',\n });\n }\n}\n\nexport async function sha256File(file: string): Promise<string> {\n const hash = createHash('sha256');\n await new Promise<void>((resolve, reject) => {\n const s = createReadStream(file);\n s.on('data', (c) => hash.update(c));\n s.on('error', reject);\n s.on('end', () => resolve());\n });\n return hash.digest('hex');\n}\n\nexport function sha256Text(text: string): string {\n return createHash('sha256').update(text).digest('hex');\n}\n\nexport function looksBinary(buf: Uint8Array): boolean {\n const n = Math.min(buf.length, 8000);\n for (let i = 0; i < n; i++) if (buf[i] === 0) return true;\n return false;\n}\n\n/** Reads a text file; returns null if binary or larger than maxBytes. */\nexport async function readTextBounded(file: string, maxBytes = 512 * 1024): Promise<string | null> {\n const stat = await fs.stat(file);\n if (stat.size > maxBytes) return null;\n const buf = await fs.readFile(file);\n if (looksBinary(buf)) return null;\n return buf.toString('utf8').replace(/^\\uFEFF/, '');\n}\n\nexport function randomId(bytes = 2): string {\n return randomBytes(bytes).toString('hex');\n}\n\nexport async function listFilesRecursive(dir: string, maxFiles = 5000): Promise<string[]> {\n const out: string[] = [];\n async function walk(d: string): Promise<void> {\n let entries;\n try {\n entries = await fs.readdir(d, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n if (out.length >= maxFiles) return;\n const full = path.join(d, e.name);\n if (e.isDirectory()) await walk(full);\n else if (e.isFile()) out.push(full);\n }\n }\n await walk(dir);\n return out;\n}\n\n/** Atomically write text only when it differs from what is on disk. Returns true if a write happened. */\nexport async function writeTextIfChanged(file: string, text: string): Promise<boolean> {\n try {\n if ((await fs.readFile(file, 'utf8')) === text) return false;\n } catch {\n /* missing: write below */\n }\n await atomicWriteFile(file, text);\n return true;\n}\n\nexport async function writeJsonIfChanged(file: string, value: unknown): Promise<boolean> {\n const text = JSON.stringify(value, null, 2) + '\\n';\n JSON.parse(text);\n return writeTextIfChanged(file, text);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"lock.js","sourceRoot":"","sources":["../../src/utils/lock.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAA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,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAChE,CAAC;AACH,CAAC","sourcesContent":["import { promises as fs, unlinkSync } from 'node:fs';\nimport path from 'node:path';\nimport { DevWorkspaceError } from '../errors/index.js';\nimport { ensureDir } from './fs.js';\nimport { onCleanup } from './cleanup.js';\n\nexport interface LockOptions {\n timeoutMs?: number;\n staleMs?: number;\n /** Lock file name under .devworkspace/local/. Long-running operations use their own lock. */\n name?: string;\n}\n\nfunction pidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (e) {\n return (e as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Exclusive advisory lock stored under .devworkspace/local/. Stale locks (dead pid or too old) are broken. */\nexport async function withLock<T>(workspaceDir: string, fn: () => Promise<T>, opts: LockOptions = {}): Promise<T> {\n const timeoutMs = opts.timeoutMs ?? 10_000;\n const staleMs = opts.staleMs ?? 60_000;\n const dir = path.join(workspaceDir, 'local');\n const lockPath = path.join(dir, opts.name ?? 'workspace.lock');\n await ensureDir(dir);\n const started = Date.now();\n let winPermRetries = 0;\n for (;;) {\n try {\n const fh = await fs.open(lockPath, 'wx');\n await fh.writeFile(JSON.stringify({ pid: process.pid, at: Date.now() }));\n await fh.close();\n break;\n } catch (e) {\n const code = (e as NodeJS.ErrnoException).code;\n // On Windows, opening a recently unlinked lock file while its handle is closing can briefly raise EPERM/EACCES.\n if (process.platform === 'win32' && (code === 'EPERM' || code === 'EACCES') && winPermRetries < 25 && Date.now() - started <= timeoutMs) {\n winPermRetries++;\n await new Promise((r) => setTimeout(r, 15 + Math.floor(Math.random() * 25)));\n continue;\n }\n if (code !== 'EEXIST') {\n throw new DevWorkspaceError('IO', 'Could not acquire the workspace lock.', { cause: e });\n }\n let stale: boolean;\n try {\n const info = JSON.parse(await fs.readFile(lockPath, 'utf8')) as { pid?: number; at?: number };\n const age = Date.now() - (info.at ?? 0);\n stale = age > staleMs || (typeof info.pid === 'number' && !pidAlive(info.pid));\n } catch {\n // Unreadable lock: another process may be mid-write, so only break it once it is old.\n try {\n stale = Date.now() - (await fs.stat(lockPath)).mtimeMs > 2000;\n } catch {\n stale = true;\n }\n }\n if (stale) {\n await fs.rm(lockPath, { force: true });\n continue;\n }\n if (Date.now() - started > timeoutMs) {\n throw new DevWorkspaceError('LOCKED', 'Another DevWorkspace process is modifying this workspace.', {\n hint: `Wait for it to finish, or delete ${path.join('.devworkspace', 'local', opts.name ?? 'workspace.lock')} if no process is running.`,\n });\n }\n await new Promise((r) => setTimeout(r, 25 + Math.floor(Math.random() * 50)));\n }\n }\n const dispose = onCleanup(() => {\n try {\n unlinkSync(lockPath);\n } catch {\n /* already gone */\n }\n });\n try {\n return await fn();\n } finally {\n dispose();\n await fs.rm(lockPath, { force: true }).catch(() => undefined);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"logger.js","sourceRoot":"","sources":["../../src/utils/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAG/C,MAAM,KAAK,GAA6B,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC;AAUjF,6EAA6E;AAC7E,MAAM,UAAU,YAAY,CAAC,KAAe,EAAE,QAAgC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC;IACjH,MAAM,IAAI,GAAG,CAAC,CAAW,EAAE,GAAW,EAAQ,EAAE;QAC9C,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,KAAK,CAAC;YAAE,KAAK,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAC5F,CAAC,CAAC;IACF,OAAO;QACL,KAAK;QACL,KAAK,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;QAC9B,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;QAC5B,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;QAC5B,KAAK,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;KAC/B,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAW,YAAY,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC","sourcesContent":["import { redact } from '../security/redact.js';\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug';\nconst ORDER: Record<LogLevel, number> = { error: 0, warn: 1, info: 2, debug: 3 };\n\nexport interface Logger {\n level: LogLevel;\n error(msg: string): void;\n warn(msg: string): void;\n info(msg: string): void;\n debug(msg: string): void;\n}\n\n/** Every message is passed through secret redaction before it is written. */\nexport function createLogger(level: LogLevel, write: (line: string) => void = (l) => process.stderr.write(l + '\\n')): Logger {\n const emit = (l: LogLevel, msg: string): void => {\n if (ORDER[l] <= ORDER[level]) write(l === 'info' ? redact(msg) : `[${l}] ${redact(msg)}`);\n };\n return {\n level,\n error: (m) => emit('error', m),\n warn: (m) => emit('warn', m),\n info: (m) => emit('info', m),\n debug: (m) => emit('debug', m),\n };\n}\n\nexport const silentLogger: Logger = createLogger('error', () => undefined);\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"paths.js","sourceRoot":"","sources":["../../src/utils/paths.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,QAAQ,IAAI,EAAE,E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C7B,IAAI,CAAC;YACH,IAAI,GAAG,MAAM,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAClC,CAAC;QAAC,MAAM,CAAC;YACP,IAAI,GAAG,SAAS,CAAC;QACnB,CAAC;QACD,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC;gBAC9B,MAAM,IAAI,iBAAiB,CAAC,aAAa,EAAE,wDAAwD,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,EAAE;oBAC1H,IAAI,EAAE,yDAAyD;iBAChE,CAAC,CAAC;YACL,CAAC;YACD,OAAO;QACT,CAAC;QACD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACnC,IAAI,MAAM,KAAK,KAAK;YAAE,OAAO;QAC7B,KAAK,GAAG,MAAM,CAAC;IACjB,CAAC;AACH,CAAC;AAED,0FAA0F;AAC1F,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,+DAA+D,CAAC,CAAC;IACzF,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACxC,CAAC","sourcesContent":["import path from 'node:path';\nimport { promises as fs } from 'node:fs';\nimport { DevWorkspaceError } from '../errors/index.js';\n\ntype PathMod = typeof path.posix;\n\n/** Normalize any path flavour to forward slashes without duplicate separators. */\nexport function toPosix(p: string): string {\n return p.replace(/\\\\/g, '/').replace(/\\/{2,}/g, '/');\n}\n\nexport function looksAbsolute(p: string): boolean {\n return /^[a-zA-Z]:[\\\\/]/.test(p) || p.startsWith('\\\\\\\\') || p.startsWith('/') || p.startsWith('\\\\');\n}\n\n/** True if target equals root or lives beneath it. Pass path.win32 / path.posix to test either flavour. */\nexport function isInside(root: string, target: string, mod: PathMod = path): boolean {\n const rel = mod.relative(root, target);\n if (rel === '') return true;\n if (mod.isAbsolute(rel)) return false;\n return rel !== '..' && !rel.startsWith('..' + mod.sep) && !rel.startsWith('../');\n}\n\nconst WINDOWS_RESERVED = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\\..*)?$/i;\n\n/**\n * Validate a portable, project-relative path (as stored in knowledge or archives).\n * Returns an error string, or null if the path is acceptable.\n */\nexport function validateRelativePath(rel: string): string | null {\n if (rel.length === 0) return 'empty path';\n if (rel.length > 240) return 'path too long';\n if (rel.includes('\\0')) return 'NUL byte in path';\n if (rel.includes('\\\\')) return 'backslash in portable path';\n if (looksAbsolute(rel)) return 'absolute path';\n\n let decoded: string;\n try {\n decoded = decodeURIComponent(rel);\n } catch {\n return 'malformed URL encoding in path';\n }\n if (decoded !== rel) {\n if (\n decoded.includes('\\\\') ||\n looksAbsolute(decoded) ||\n decoded.includes('\\0') ||\n decoded.split('/').some((seg) => seg === '..' || seg === '.' || WINDOWS_RESERVED.test(seg))\n ) {\n return 'encoded traversal or absolute path';\n }\n }\n\n for (const s of rel.split('/')) {\n if (s === '') return 'empty path segment';\n if (s === '..') return 'parent traversal';\n if (s === '.') return 'dot segment';\n if (WINDOWS_RESERVED.test(s)) return 'Windows reserved device name';\n\n let ds: string;\n try {\n ds = decodeURIComponent(s);\n } catch {\n return 'malformed URL encoding in path';\n }\n if (ds === '..' || ds === '.') return 'parent traversal';\n if (WINDOWS_RESERVED.test(ds)) return 'Windows reserved device name';\n\n // eslint-disable-next-line no-control-regex\n if (/[<>:\"|?*\\u0000-\\u001f]/.test(s)) return 'characters not portable to Windows';\n if (/[. ]$/.test(s)) return 'segment ends with dot or space';\n }\n return null;\n}\n\nexport function resolveInside(root: string, rel: string, mod: PathMod = path): string {\n const posix = toPosix(rel);\n const err = validateRelativePath(posix);\n if (err) {\n throw new DevWorkspaceError('UNSAFE_PATH', `Refusing unsafe path \"${rel}\" (${err}).`, {\n hint: 'Use paths relative to the project root without \"..\" segments.',\n });\n }\n const full = mod.resolve(root, ...posix.split('/'));\n if (!isInside(root, full, mod)) {\n throw new DevWorkspaceError('UNSAFE_PATH', `Path \"${rel}\" escapes the project root.`);\n }\n return full;\n}\n\n/** Fails if the deepest existing ancestor of target resolves (through symlinks) outside root. */\nexport async function assertNoSymlinkEscape(root: string, target: string): Promise<void> {\n const realRoot = await fs.realpath(root);\n let probe = target;\n for (;;) {\n let real: string | undefined;\n try {\n real = await fs.realpath(probe);\n } catch {\n real = undefined;\n }\n if (real !== undefined) {\n if (!isInside(realRoot, real)) {\n throw new DevWorkspaceError('UNSAFE_PATH', `Path resolves outside the project through a symlink: ${path.basename(target)}`, {\n hint: 'Remove the symlink or choose a path inside the project.',\n });\n }\n return;\n }\n const parent = path.dirname(probe);\n if (parent === probe) return;\n probe = parent;\n }\n}\n\n/** Detects machine-specific absolute paths that must not appear in portable knowledge. */\nexport function findAbsolutePaths(text: string): string[] {\n const hits = text.match(/(?:\\b[A-Za-z]:\\\\[^\\s\"'`<>|]+|\\/(?:Users|home)\\/[^\\s\"'`<>|]+)/g);\n return hits ? [...new Set(hits)] : [];\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"proc.js","sourceRoot":"","sources":["../../src/utils/proc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,IAAI,MAAM,WAAW,CAAC;AAwB7B;;;GAGG;AACH,MAAM,UAAU,GAAG,CAAC,OAAe,EAAE,IAAc,EAAE,OAAmB,EAAE;IACxE,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,MAAM,CAAC;IAC3C,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;IAClD,OAAO,IAAI,OAAO,CAAC,C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AAQ,CAAC,GAAG,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YAC7H,IAAI,CAAC;gBACH,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBACpC,IAAI,EAAE,CAAC,MAAM,EAAE;oBAAE,OAAO,SAAS,CAAC;YACpC,CAAC;YAAC,MAAM,CAAC;gBACP,kBAAkB;YACpB,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,qHAAqH;AACrH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import { spawn } from 'node:child_process';\nimport { promises as fs } from 'node:fs';\nimport path from 'node:path';\n\nexport interface RunResult {\n ok: boolean;\n code: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n aborted?: boolean;\n error?: string;\n}\n\nexport interface RunOptions {\n cwd?: string;\n timeoutMs?: number;\n maxBytes?: number;\n /** Extra environment variables merged over process.env (undefined values unset the variable). */\n env?: Record<string, string | undefined>;\n /** Abort (kill) the process when the signal fires. */\n signal?: AbortSignal;\n /** Windows only: pass the argument string through unmodified (used for cmd.exe /c with pre-validated arguments). */\n windowsVerbatimArguments?: boolean;\n}\n\n/**\n * Run an executable with an argument array. Never uses a shell, so project- or\n * user-supplied values cannot be interpreted as shell syntax.\n */\nexport function run(command: string, args: string[], opts: RunOptions = {}): Promise<RunResult> {\n const timeoutMs = opts.timeoutMs ?? 15_000;\n const maxBytes = opts.maxBytes ?? 4 * 1024 * 1024;\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n let timedOut = false;\n let aborted = false;\n let settled = false;\n // eslint-disable-next-line prefer-const -- assigned after spawn; finish() may run first if spawn throws\n let timer: NodeJS.Timeout | undefined;\n const onAbort = (): void => {\n aborted = true;\n child?.kill();\n };\n const finish = (r: RunResult): void => {\n if (settled) return;\n settled = true;\n if (timer) clearTimeout(timer);\n opts.signal?.removeEventListener('abort', onAbort);\n resolve(aborted ? { ...r, ok: false, aborted: true } : r);\n };\n let child: ReturnType<typeof spawn> | undefined;\n if (opts.signal?.aborted) {\n finish({ ok: false, code: null, stdout, stderr, timedOut: false, aborted: true, error: 'aborted' });\n return;\n }\n try {\n const env = opts.env ? { ...process.env, ...opts.env } : process.env;\n for (const [k, v] of Object.entries(env)) if (v === undefined) delete env[k];\n child = spawn(command, args, {\n cwd: opts.cwd,\n env,\n shell: false,\n windowsHide: true,\n windowsVerbatimArguments: opts.windowsVerbatimArguments,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n } catch (e) {\n finish({ ok: false, code: null, stdout, stderr, timedOut: false, error: (e as Error).message });\n return;\n }\n const c = child;\n timer = setTimeout(() => {\n timedOut = true;\n c.kill();\n }, timeoutMs);\n opts.signal?.addEventListener('abort', onAbort, { once: true });\n c.stdout?.on('data', (d: Buffer) => {\n if (stdout.length < maxBytes) stdout += d.toString('utf8');\n });\n c.stderr?.on('data', (d: Buffer) => {\n if (stderr.length < maxBytes) stderr += d.toString('utf8');\n });\n c.on('error', (e) => finish({ ok: false, code: null, stdout, stderr, timedOut, error: e.message }));\n c.on('close', (code) => finish({ ok: code === 0 && !timedOut && !aborted, code, stdout, stderr, timedOut }));\n });\n}\n\n/** Locate an executable on PATH (honouring PATHEXT on Windows) without executing anything. */\nexport async function which(name: string, env: NodeJS.ProcessEnv = process.env): Promise<string | null> {\n if (!name || typeof name !== 'string') return null;\n const isWin = process.platform === 'win32';\n const exts = isWin ? (env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean) : [''];\n const hasExt = isWin && exts.some((e) => name.toLowerCase().endsWith(e.toLowerCase()));\n const extsToTry = isWin ? (hasExt ? ['', ...exts] : [...exts, '']) : [''];\n\n if (path.isAbsolute(name) || name.includes('/') || (isWin && name.includes('\\\\'))) {\n for (const ext of extsToTry) {\n const candidate = ext && !name.toLowerCase().endsWith(ext.toLowerCase()) ? name + ext : name;\n try {\n const st = await fs.stat(candidate);\n if (st.isFile()) return candidate;\n } catch {\n /* keep looking */\n }\n }\n return null;\n }\n\n const pathVar = env.PATH ?? env.Path ?? '';\n for (const dir of pathVar.split(path.delimiter).filter(Boolean)) {\n for (const ext of extsToTry) {\n const candidate = ext && !name.toLowerCase().endsWith(ext.toLowerCase()) ? path.join(dir, name + ext) : path.join(dir, name);\n try {\n const st = await fs.stat(candidate);\n if (st.isFile()) return candidate;\n } catch {\n /* keep looking */\n }\n }\n }\n return null;\n}\n\n/** .cmd/.bat shims need a shell on Windows. They are only run through the validated path in integrations/exec.ts. */\nexport function isShellShim(file: string): boolean {\n return /\\.(cmd|bat)$/i.test(file);\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"safety.js","sourceRoot":"","sources":["../../src/verification/safety.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAE7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAG3E,qEAAqE;AACrE,MAAM,YAAY,GAA2B;IAC3C,EAAE,EAAE,YAAY;IAChB,QAAQ,EAAE,YAAY;IACtB,aAAa,EAAE,gBAAgB;IAC/B,MAAM,EAAE,gBAAgB;IACxB,gBAAgB,EAAE,gBAAgB;IAClC,OAAO,EAAE,gBAAgB;IACzB,SAAS,EAAE,gBAAgB;IAC3B,IAAI,EAAE,gBAAgB;IACtB,QAAQ,EAAE,S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E,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC;IAC3E,MAAM,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,aAAa,EAAE,CAAC,EAAE,YAAY,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,EAAwB,CAAC,CAAC;AACzG,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iBAAiB,CAAC,EAAM,EAAE,GAAW;IACzD,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,EAAE,CAAC,CAAC;IAClC,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,GAAG,CAAC,CAAC;IAClD,IAAI,IAAI,CAAC,MAAM,KAAK,GAAG,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC7C,MAAM,eAAe,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,aAAa,EAAE,CAAC,EAAE,YAAY,EAAE,IAAI,EAAwB,CAAC,CAAC;IAChG,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,KAA2B,EAAE,GAAW,EAAE,KAAa;IAChF,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,GAAG,IAAI,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;AAC1E,CAAC","sourcesContent":["import path from 'node:path';\nimport type { CommandEntry } from '../config/schemas.js';\nimport { DevWorkspaceError } from '../errors/index.js';\nimport { containsSecret } from '../security/redact.js';\nimport { safeReadText } from '../security/files.js';\nimport { atomicWriteJson, pathExists, readJsonFile } from '../utils/fs.js';\nimport type { Ws } from '../core/workspace.js';\n\n/** Dependencies that mean a package talks to a database or queue. */\nconst SERVICE_DEPS: Record<string, string> = {\n pg: 'PostgreSQL',\n postgres: 'PostgreSQL',\n 'drizzle-orm': 'a SQL database',\n prisma: 'a SQL database',\n '@prisma/client': 'a SQL database',\n typeorm: 'a SQL database',\n sequelize: 'a SQL database',\n knex: 'a SQL database',\n mongoose: 'MongoDB',\n mongodb: 'MongoDB',\n redis: 'Redis',\n ioredis: 'Redis',\n bullmq: 'Redis',\n bull: 'Redis',\n};\n\n/** Words that make a command destructive or schema-changing no matter which check it is filed under. */\nconst DESTRUCTIVE = /(?:^|[\\s:/_-])(?:drop|truncate|flushall|flushdb|reset|seed|migrate)(?:$|[\\s:/_.-])|db:push|--force|rm\\s+-rf/i;\n/** Checks whose job is to exercise real services. They need a declared test environment. */\nconst SERVICE_CHECKS = new Set(['integration', 'security', 'e2e']);\n\nexport type Safety = 'safe' | 'needs-test-environment' | 'blocked';\n\nexport interface CommandSafety {\n safety: Safety;\n reasons: string[];\n /** Services the package is known to use (from its manifest), for the explanation only. */\n services: string[];\n}\n\nexport interface ManifestEvidence {\n scriptBody: string | null;\n services: string[];\n hasCredentialFile: boolean;\n}\n\n/** Read the package manifest next to a command: the script it runs and the services the package depends on. Never reads .env files. */\nexport async function readManifestEvidence(root: string, entry: CommandEntry): Promise<ManifestEvidence> {\n const dir = entry.cwd && entry.cwd !== '.' ? entry.cwd : '';\n const manifest = dir ? `${dir}/package.json` : 'package.json';\n let scriptBody: string | null = null;\n const services = new Set<string>();\n try {\n const text = await safeReadText(root, manifest, 1024 * 1024);\n const json = text ? (JSON.parse(text) as { scripts?: Record<string, string>; dependencies?: Record<string, string>; devDependencies?: Record<string, string> }) : null;\n const script = /#scripts\\.(.+)$/.exec(entry.source ?? '')?.[1];\n if (json && script && typeof json.scripts?.[script] === 'string') scriptBody = json.scripts[script]!;\n for (const dep of Object.keys({ ...json?.dependencies, ...json?.devDependencies })) if (SERVICE_DEPS[dep]) services.add(SERVICE_DEPS[dep]!);\n } catch {\n /* unreadable manifest: no evidence */\n }\n let hasCredentialFile = false;\n for (const name of ['.env', '.env.local', '.env.test', '.env.development']) {\n if (await pathExists(path.join(root, ...(dir ? [dir] : []), name))) hasCredentialFile = true;\n }\n // \"a SQL database\" is only the fallback label for an ORM; drop it once a specific database is known.\n if (services.size > 1) services.delete('a SQL database');\n return { scriptBody, services: [...services].sort(), hasCredentialFile };\n}\n\n/**\n * Decide whether DevWorkspace may run a contract command by itself. Pure; no file is read here.\n * - blocked: modifies project files, changes a schema/data set, or is destructive. Never run automatically.\n * - needs-test-environment: exercises real services or may (a catch-all `test` in a package that uses a database).\n * Runs only after the user declared a test environment for that package and check.\n * - safe: typecheck, lint, build, unit tests and read-only format checks.\n * A database is never judged safe from its name; DevWorkspace does not read connection settings at all.\n */\nexport function classifyCommand(entry: CommandEntry, evidence: ManifestEvidence): CommandSafety {\n const reasons: string[] = [];\n const services = evidence.services;\n const text = `${entry.command ?? ''} ${evidence.scriptBody ?? ''}`;\n if (entry.mutates) return { safety: 'blocked', reasons: ['it modifies project files; DevWorkspace never runs formatters or fixers'], services };\n if (entry.id === 'migrations') return { safety: 'blocked', reasons: ['it changes a database schema; DevWorkspace never runs migrations'], services };\n if (DESTRUCTIVE.test(text)) return { safety: 'blocked', reasons: ['its definition mentions a destructive or schema-changing operation (drop/reset/seed/migrate/flush)'], services };\n if (SERVICE_CHECKS.has(entry.id)) {\n reasons.push(`${entry.id} tests exercise real services${services.length ? ` (the package uses ${services.join(', ')})` : ''}`);\n } else if (entry.id === 'unit' && services.length > 0 && /(?:^|\\s)(?:run\\s+)?test(?:\\s|$)/.test(entry.command ?? '') && !/unit/.test(entry.command ?? '')) {\n reasons.push(`the catch-all test script of a package that uses ${services.join(', ')} may include integration tests`);\n }\n if (reasons.length === 0) return { safety: 'safe', reasons: [], services };\n if (evidence.hasCredentialFile) reasons.push('a credential file exists in the package (never read), so the database target cannot be verified');\n else reasons.push('the database target cannot be verified');\n return { safety: 'needs-test-environment', reasons, services };\n}\n\n// ---------- explicit test-environment declarations (machine-local, never committed) ----------\n\nexport interface TestEnvDeclaration {\n /** Package directory relative to the project root; \".\" for the root. */\n package: string;\n checks: string[];\n /** Human description of the target, e.g. \"docker compose test stack on this laptop\". Never a connection string. */\n target: string;\n declaredAt: string;\n}\n\ninterface TestEnvFile {\n schemaVersion: 1;\n declarations: TestEnvDeclaration[];\n}\n\nconst file = (ws: Ws): string => path.join(ws.localDir, 'test-environment.json');\n\nexport async function loadTestEnv(ws: Ws): Promise<TestEnvDeclaration[]> {\n if (!(await pathExists(file(ws)))) return [];\n const raw = (await readJsonFile(file(ws))) as Partial<TestEnvFile>;\n return Array.isArray(raw.declarations) ? raw.declarations : [];\n}\n\nexport function assertSafeTarget(target: string): void {\n const t = target.trim();\n if (t.length < 5 || t.length > 200) throw new DevWorkspaceError('USAGE', '--target must be a short description (5-200 characters) of the test environment.');\n if (containsSecret(t) || /[a-z][a-z0-9+.-]*:\\/\\/\\S+/i.test(t) || /(?:password|passwd|pwd|token|secret)\\s*[=:]/i.test(t)) {\n throw new DevWorkspaceError('SECURITY', 'The target description looks like a connection string or credential; refusing to store it.', {\n hint: 'Describe the environment in words (for example \"disposable docker compose stack\"), not how to connect to it.',\n });\n }\n}\n\nexport async function saveDeclaration(ws: Ws, d: TestEnvDeclaration): Promise<void> {\n const all = (await loadTestEnv(ws)).filter((x) => x.package !== d.package);\n await atomicWriteJson(file(ws), { schemaVersion: 1, declarations: [...all, d] } satisfies TestEnvFile);\n}\n\nexport async function removeDeclaration(ws: Ws, pkg: string): Promise<boolean> {\n const all = await loadTestEnv(ws);\n const rest = all.filter((x) => x.package !== pkg);\n if (rest.length === all.length) return false;\n await atomicWriteJson(file(ws), { schemaVersion: 1, declarations: rest } satisfies TestEnvFile);\n return true;\n}\n\nexport function isDeclared(decls: TestEnvDeclaration[], pkg: string, check: string): TestEnvDeclaration | undefined {\n return decls.find((d) => d.package === pkg && d.checks.includes(check));\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"scope.js","sourceRoot":"","sources":["../../src/verification/scope.ts"],"names":[],"mappings":"AAAA,OA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KAAK,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC;IACtD,MAAM,IAAI,GAAG,CAAC,CAAS,EAAU,EAAE,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;IACzD,MAAM,GAAG,GAA2B,EAAE,GAAG,EAAE,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;IACpF,KAAK,MAAM,CAAC,IAAI,IAAI,EAAE,CAAC;QACrB,MAAM,IAAI,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC;QACjD,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC;YAAE,GAAG,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,CAAC,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAClH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport type { CommandEntry } from '../config/schemas.js';\nimport { gitAvailable, parsePorcelainZ } from '../git/git.js';\nimport { isSensitiveFile } from '../security/files.js';\nimport type { TaskScope } from '../tasks/task.js';\nimport { sha256File, sha256Text } from '../utils/fs.js';\nimport { run } from '../utils/proc.js';\n\nconst MAX_TRACKED_FILES = 2000;\nconst MAX_HASH_BYTES = 8 * 1024 * 1024;\n/** Documentation and tool-managed folders never decide which package's checks apply. */\nconst NOT_CODE = /^(?:\\.devworkspace|\\.claude|\\.cursor|\\.github|graphify-out)\\/|\\.(?:md|mdx|mdc|rst|txt)$/i;\n\nexport type ChangeMap = Record<string, string>;\n\nasync function git(root: string, args: string[]): Promise<string | null> {\n const r = await run('git', args, { cwd: root, timeoutMs: 30_000 });\n return r.ok ? r.stdout : null;\n}\n\nasync function fileFingerprint(root: string, rel: string): Promise<string> {\n const full = path.join(root, ...rel.split('/'));\n try {\n const st = await fs.lstat(full);\n if (!st.isFile()) return 'not-a-file';\n if (st.size > MAX_HASH_BYTES) return `large:${st.size}:${Math.floor(st.mtimeMs)}`;\n return await sha256File(full);\n } catch {\n return 'deleted';\n }\n}\n\n/** Files that differ from HEAD right now (modified, staged or untracked), project-relative, with a content hash. */\nexport async function dirtyFiles(root: string): Promise<{ head: string | null; files: ChangeMap } | null> {\n if (!(await gitAvailable())) return null;\n if ((await git(root, ['rev-parse', '--is-inside-work-tree']))?.trim() !== 'true') return null;\n const prefix = ((await git(root, ['rev-parse', '--show-prefix'])) ?? '').trim();\n const head = ((await git(root, ['rev-parse', 'HEAD'])) ?? '').trim() || null;\n const status = await git(root, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);\n if (status === null) return null;\n const files: ChangeMap = {};\n for (const e of parsePorcelainZ(status)) {\n if (e.xy === '!!' || !e.path.startsWith(prefix)) continue;\n const rel = e.path.slice(prefix.length);\n if (NOT_CODE.test(rel) || isSensitiveFile(rel)) continue;\n if (Object.keys(files).length >= MAX_TRACKED_FILES) break;\n files[rel] = await fileFingerprint(root, rel);\n }\n return { head, files };\n}\n\n/** Snapshot taken when a task is created: what is already modified is not the task's doing. */\nexport async function captureScope(root: string, now: string): Promise<TaskScope> {\n const d = await dirtyFiles(root);\n return { capturedAt: now, head: d?.head ?? null, baseline: d?.files ?? {} };\n}\n\n/** Project-relative files committed since `head` (so committing during a task does not hide its changes). */\nasync function committedSince(root: string, head: string): Promise<string[] | null> {\n const prefix = ((await git(root, ['rev-parse', '--show-prefix'])) ?? '').trim();\n const out = await git(root, ['diff', '--name-only', '-z', head, 'HEAD']);\n if (out === null) return null;\n return out.split('\\0').filter((f) => f && f.startsWith(prefix)).map((f) => f.slice(prefix.length));\n}\n\n/** Files that changed since the task started, with their current hashes. Null when that cannot be determined. */\nexport async function changedSince(root: string, scope: TaskScope): Promise<ChangeMap | null> {\n const now = await dirtyFiles(root);\n if (!now) return null;\n const changed: ChangeMap = {};\n for (const [rel, hash] of Object.entries(now.files)) if (scope.baseline[rel] !== hash) changed[rel] = hash;\n // A file that was modified at the start and has since been cleaned up (committed or reverted) also changed.\n for (const rel of Object.keys(scope.baseline)) if (!(rel in now.files)) changed[rel] = await fileFingerprint(root, rel);\n if (scope.head && now.head && scope.head !== now.head) {\n const committed = await committedSince(root, scope.head);\n if (committed === null) return null;\n for (const rel of committed) if (!NOT_CODE.test(rel) && !isSensitiveFile(rel) && !(rel in changed)) changed[rel] = await fileFingerprint(root, rel);\n }\n return changed;\n}\n\n/** Directories (relative to the project root) that have their own checks in the contract, longest first. */\nexport function packageDirs(contract: CommandEntry[]): string[] {\n const dirs = new Set<string>();\n for (const c of contract) if (c.available && c.cwd && c.cwd !== '.') dirs.add(c.cwd);\n return [...dirs].sort((a, b) => b.length - a.length || a.localeCompare(b));\n}\n\n/**\n * Fingerprint of the changes inside each package. A change under a package belongs to it; a change outside every package\n * (root config, shared tooling) belongs to all of them. \".\" covers everything. Returns null when nothing is known.\n */\nexport function scopeByPackage(changes: ChangeMap | null, contract: CommandEntry[]): Record<string, string> | null {\n if (!changes) return null;\n const files = Object.keys(changes).filter((f) => !NOT_CODE.test(f)).sort();\n if (files.length === 0) return null;\n const dirs = packageDirs(contract);\n const owner = (f: string): string | null => dirs.find((d) => f === d || f.startsWith(`${d}/`)) ?? null;\n const shared = files.filter((f) => owner(f) === null);\n const line = (f: string): string => `${f}:${changes[f]}`;\n const out: Record<string, string> = { '.': sha256Text(files.map(line).join('\\n')) };\n for (const d of dirs) {\n const mine = files.filter((f) => owner(f) === d);\n if (mine.length > 0 || shared.length > 0) out[d] = sha256Text([...mine, ...shared].sort().map(line).join('\\n'));\n }\n return out;\n}\n"]}