@telora/factory 0.4.5

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 (301) hide show
  1. package/dist/audit.d.ts +69 -0
  2. package/dist/audit.d.ts.map +1 -0
  3. package/dist/audit.js +376 -0
  4. package/dist/audit.js.map +1 -0
  5. package/dist/builder-completion.d.ts +35 -0
  6. package/dist/builder-completion.d.ts.map +1 -0
  7. package/dist/builder-completion.js +375 -0
  8. package/dist/builder-completion.js.map +1 -0
  9. package/dist/builder-spawner.d.ts +40 -0
  10. package/dist/builder-spawner.d.ts.map +1 -0
  11. package/dist/builder-spawner.js +493 -0
  12. package/dist/builder-spawner.js.map +1 -0
  13. package/dist/completion-gate.d.ts +52 -0
  14. package/dist/completion-gate.d.ts.map +1 -0
  15. package/dist/completion-gate.js +336 -0
  16. package/dist/completion-gate.js.map +1 -0
  17. package/dist/completion-report.d.ts +36 -0
  18. package/dist/completion-report.d.ts.map +1 -0
  19. package/dist/completion-report.js +348 -0
  20. package/dist/completion-report.js.map +1 -0
  21. package/dist/completion.d.ts +58 -0
  22. package/dist/completion.d.ts.map +1 -0
  23. package/dist/completion.js +287 -0
  24. package/dist/completion.js.map +1 -0
  25. package/dist/config.d.ts +16 -0
  26. package/dist/config.d.ts.map +1 -0
  27. package/dist/config.js +57 -0
  28. package/dist/config.js.map +1 -0
  29. package/dist/context-manager.d.ts +152 -0
  30. package/dist/context-manager.d.ts.map +1 -0
  31. package/dist/context-manager.js +421 -0
  32. package/dist/context-manager.js.map +1 -0
  33. package/dist/crash-detection.d.ts +70 -0
  34. package/dist/crash-detection.d.ts.map +1 -0
  35. package/dist/crash-detection.js +123 -0
  36. package/dist/crash-detection.js.map +1 -0
  37. package/dist/crash-recovery.d.ts +83 -0
  38. package/dist/crash-recovery.d.ts.map +1 -0
  39. package/dist/crash-recovery.js +522 -0
  40. package/dist/crash-recovery.js.map +1 -0
  41. package/dist/crash-resolution.d.ts +34 -0
  42. package/dist/crash-resolution.d.ts.map +1 -0
  43. package/dist/crash-resolution.js +382 -0
  44. package/dist/crash-resolution.js.map +1 -0
  45. package/dist/escalation.d.ts +150 -0
  46. package/dist/escalation.d.ts.map +1 -0
  47. package/dist/escalation.js +352 -0
  48. package/dist/escalation.js.map +1 -0
  49. package/dist/execution-target.d.ts +31 -0
  50. package/dist/execution-target.d.ts.map +1 -0
  51. package/dist/execution-target.js +71 -0
  52. package/dist/execution-target.js.map +1 -0
  53. package/dist/execution-unit-init.d.ts +28 -0
  54. package/dist/execution-unit-init.d.ts.map +1 -0
  55. package/dist/execution-unit-init.js +115 -0
  56. package/dist/execution-unit-init.js.map +1 -0
  57. package/dist/execution.d.ts +17 -0
  58. package/dist/execution.d.ts.map +1 -0
  59. package/dist/execution.js +20 -0
  60. package/dist/execution.js.map +1 -0
  61. package/dist/factory-engine.d.ts +100 -0
  62. package/dist/factory-engine.d.ts.map +1 -0
  63. package/dist/factory-engine.js +243 -0
  64. package/dist/factory-engine.js.map +1 -0
  65. package/dist/gap-detection.d.ts +43 -0
  66. package/dist/gap-detection.d.ts.map +1 -0
  67. package/dist/gap-detection.js +149 -0
  68. package/dist/gap-detection.js.map +1 -0
  69. package/dist/gate-context.d.ts +23 -0
  70. package/dist/gate-context.d.ts.map +1 -0
  71. package/dist/gate-context.js +63 -0
  72. package/dist/gate-context.js.map +1 -0
  73. package/dist/gate-engine.d.ts +55 -0
  74. package/dist/gate-engine.d.ts.map +1 -0
  75. package/dist/gate-engine.js +191 -0
  76. package/dist/gate-engine.js.map +1 -0
  77. package/dist/gates/adversarial.d.ts +59 -0
  78. package/dist/gates/adversarial.d.ts.map +1 -0
  79. package/dist/gates/adversarial.js +426 -0
  80. package/dist/gates/adversarial.js.map +1 -0
  81. package/dist/gates/adversary-spawner.d.ts +35 -0
  82. package/dist/gates/adversary-spawner.d.ts.map +1 -0
  83. package/dist/gates/adversary-spawner.js +286 -0
  84. package/dist/gates/adversary-spawner.js.map +1 -0
  85. package/dist/gates/adversary-test-dir.d.ts +41 -0
  86. package/dist/gates/adversary-test-dir.d.ts.map +1 -0
  87. package/dist/gates/adversary-test-dir.js +150 -0
  88. package/dist/gates/adversary-test-dir.js.map +1 -0
  89. package/dist/gates/behavioral-parser.d.ts +32 -0
  90. package/dist/gates/behavioral-parser.d.ts.map +1 -0
  91. package/dist/gates/behavioral-parser.js +190 -0
  92. package/dist/gates/behavioral-parser.js.map +1 -0
  93. package/dist/gates/behavioral-runner.d.ts +36 -0
  94. package/dist/gates/behavioral-runner.d.ts.map +1 -0
  95. package/dist/gates/behavioral-runner.js +306 -0
  96. package/dist/gates/behavioral-runner.js.map +1 -0
  97. package/dist/gates/behavioral.d.ts +37 -0
  98. package/dist/gates/behavioral.d.ts.map +1 -0
  99. package/dist/gates/behavioral.js +485 -0
  100. package/dist/gates/behavioral.js.map +1 -0
  101. package/dist/gates/deterministic.d.ts +24 -0
  102. package/dist/gates/deterministic.d.ts.map +1 -0
  103. package/dist/gates/deterministic.js +186 -0
  104. package/dist/gates/deterministic.js.map +1 -0
  105. package/dist/git-factory.d.ts +59 -0
  106. package/dist/git-factory.d.ts.map +1 -0
  107. package/dist/git-factory.js +102 -0
  108. package/dist/git-factory.js.map +1 -0
  109. package/dist/guard-evaluation.d.ts +48 -0
  110. package/dist/guard-evaluation.d.ts.map +1 -0
  111. package/dist/guard-evaluation.js +416 -0
  112. package/dist/guard-evaluation.js.map +1 -0
  113. package/dist/index.d.ts +30 -0
  114. package/dist/index.d.ts.map +1 -0
  115. package/dist/index.js +39 -0
  116. package/dist/index.js.map +1 -0
  117. package/dist/instance-completion.d.ts +34 -0
  118. package/dist/instance-completion.d.ts.map +1 -0
  119. package/dist/instance-completion.js +366 -0
  120. package/dist/instance-completion.js.map +1 -0
  121. package/dist/instance-lifecycle.d.ts +15 -0
  122. package/dist/instance-lifecycle.d.ts.map +1 -0
  123. package/dist/instance-lifecycle.js +18 -0
  124. package/dist/instance-lifecycle.js.map +1 -0
  125. package/dist/instance-phase-dispatch.d.ts +75 -0
  126. package/dist/instance-phase-dispatch.d.ts.map +1 -0
  127. package/dist/instance-phase-dispatch.js +674 -0
  128. package/dist/instance-phase-dispatch.js.map +1 -0
  129. package/dist/instance-poll-loop.d.ts +43 -0
  130. package/dist/instance-poll-loop.d.ts.map +1 -0
  131. package/dist/instance-poll-loop.js +360 -0
  132. package/dist/instance-poll-loop.js.map +1 -0
  133. package/dist/instance-state-machine.d.ts +52 -0
  134. package/dist/instance-state-machine.d.ts.map +1 -0
  135. package/dist/instance-state-machine.js +235 -0
  136. package/dist/instance-state-machine.js.map +1 -0
  137. package/dist/log-manager.d.ts +28 -0
  138. package/dist/log-manager.d.ts.map +1 -0
  139. package/dist/log-manager.js +71 -0
  140. package/dist/log-manager.js.map +1 -0
  141. package/dist/pipeline-evaluator.d.ts +61 -0
  142. package/dist/pipeline-evaluator.d.ts.map +1 -0
  143. package/dist/pipeline-evaluator.js +107 -0
  144. package/dist/pipeline-evaluator.js.map +1 -0
  145. package/dist/pipeline-metrics.d.ts +52 -0
  146. package/dist/pipeline-metrics.d.ts.map +1 -0
  147. package/dist/pipeline-metrics.js +40 -0
  148. package/dist/pipeline-metrics.js.map +1 -0
  149. package/dist/pipeline-traversal.d.ts +43 -0
  150. package/dist/pipeline-traversal.d.ts.map +1 -0
  151. package/dist/pipeline-traversal.js +68 -0
  152. package/dist/pipeline-traversal.js.map +1 -0
  153. package/dist/plan-parser.d.ts +76 -0
  154. package/dist/plan-parser.d.ts.map +1 -0
  155. package/dist/plan-parser.js +223 -0
  156. package/dist/plan-parser.js.map +1 -0
  157. package/dist/planning-phase.d.ts +52 -0
  158. package/dist/planning-phase.d.ts.map +1 -0
  159. package/dist/planning-phase.js +444 -0
  160. package/dist/planning-phase.js.map +1 -0
  161. package/dist/planning-prompt.d.ts +64 -0
  162. package/dist/planning-prompt.d.ts.map +1 -0
  163. package/dist/planning-prompt.js +251 -0
  164. package/dist/planning-prompt.js.map +1 -0
  165. package/dist/planning.d.ts +16 -0
  166. package/dist/planning.d.ts.map +1 -0
  167. package/dist/planning.js +17 -0
  168. package/dist/planning.js.map +1 -0
  169. package/dist/process-runner.d.ts +41 -0
  170. package/dist/process-runner.d.ts.map +1 -0
  171. package/dist/process-runner.js +81 -0
  172. package/dist/process-runner.js.map +1 -0
  173. package/dist/product-config.d.ts +34 -0
  174. package/dist/product-config.d.ts.map +1 -0
  175. package/dist/product-config.js +43 -0
  176. package/dist/product-config.js.map +1 -0
  177. package/dist/queries/cycle-evaluations.d.ts +23 -0
  178. package/dist/queries/cycle-evaluations.d.ts.map +1 -0
  179. package/dist/queries/cycle-evaluations.js +37 -0
  180. package/dist/queries/cycle-evaluations.js.map +1 -0
  181. package/dist/queries/escalations.d.ts +30 -0
  182. package/dist/queries/escalations.d.ts.map +1 -0
  183. package/dist/queries/escalations.js +42 -0
  184. package/dist/queries/escalations.js.map +1 -0
  185. package/dist/queries/execution-units.d.ts +76 -0
  186. package/dist/queries/execution-units.d.ts.map +1 -0
  187. package/dist/queries/execution-units.js +109 -0
  188. package/dist/queries/execution-units.js.map +1 -0
  189. package/dist/queries/gate-results.d.ts +32 -0
  190. package/dist/queries/gate-results.d.ts.map +1 -0
  191. package/dist/queries/gate-results.js +44 -0
  192. package/dist/queries/gate-results.js.map +1 -0
  193. package/dist/queries/instances.d.ts +51 -0
  194. package/dist/queries/instances.d.ts.map +1 -0
  195. package/dist/queries/instances.js +77 -0
  196. package/dist/queries/instances.js.map +1 -0
  197. package/dist/queries/sessions.d.ts +50 -0
  198. package/dist/queries/sessions.d.ts.map +1 -0
  199. package/dist/queries/sessions.js +81 -0
  200. package/dist/queries/sessions.js.map +1 -0
  201. package/dist/queries/shared.d.ts +38 -0
  202. package/dist/queries/shared.d.ts.map +1 -0
  203. package/dist/queries/shared.js +119 -0
  204. package/dist/queries/shared.js.map +1 -0
  205. package/dist/queries/specs.d.ts +12 -0
  206. package/dist/queries/specs.d.ts.map +1 -0
  207. package/dist/queries/specs.js +21 -0
  208. package/dist/queries/specs.js.map +1 -0
  209. package/dist/queries/strategies.d.ts +14 -0
  210. package/dist/queries/strategies.d.ts.map +1 -0
  211. package/dist/queries/strategies.js +18 -0
  212. package/dist/queries/strategies.js.map +1 -0
  213. package/dist/queries/work-units.d.ts +42 -0
  214. package/dist/queries/work-units.d.ts.map +1 -0
  215. package/dist/queries/work-units.js +57 -0
  216. package/dist/queries/work-units.js.map +1 -0
  217. package/dist/queries/workflows.d.ts +29 -0
  218. package/dist/queries/workflows.d.ts.map +1 -0
  219. package/dist/queries/workflows.js +103 -0
  220. package/dist/queries/workflows.js.map +1 -0
  221. package/dist/remediation-units.d.ts +40 -0
  222. package/dist/remediation-units.d.ts.map +1 -0
  223. package/dist/remediation-units.js +263 -0
  224. package/dist/remediation-units.js.map +1 -0
  225. package/dist/replanning.d.ts +72 -0
  226. package/dist/replanning.d.ts.map +1 -0
  227. package/dist/replanning.js +403 -0
  228. package/dist/replanning.js.map +1 -0
  229. package/dist/resource-limits.d.ts +62 -0
  230. package/dist/resource-limits.d.ts.map +1 -0
  231. package/dist/resource-limits.js +322 -0
  232. package/dist/resource-limits.js.map +1 -0
  233. package/dist/scheduler.d.ts +98 -0
  234. package/dist/scheduler.d.ts.map +1 -0
  235. package/dist/scheduler.js +203 -0
  236. package/dist/scheduler.js.map +1 -0
  237. package/dist/session-adapter.d.ts +89 -0
  238. package/dist/session-adapter.d.ts.map +1 -0
  239. package/dist/session-adapter.js +108 -0
  240. package/dist/session-adapter.js.map +1 -0
  241. package/dist/sop-generator.d.ts +29 -0
  242. package/dist/sop-generator.d.ts.map +1 -0
  243. package/dist/sop-generator.js +235 -0
  244. package/dist/sop-generator.js.map +1 -0
  245. package/dist/spec-profiles.d.ts +41 -0
  246. package/dist/spec-profiles.d.ts.map +1 -0
  247. package/dist/spec-profiles.js +131 -0
  248. package/dist/spec-profiles.js.map +1 -0
  249. package/dist/strategy-design-graph.d.ts +23 -0
  250. package/dist/strategy-design-graph.d.ts.map +1 -0
  251. package/dist/strategy-design-graph.js +205 -0
  252. package/dist/strategy-design-graph.js.map +1 -0
  253. package/dist/strategy-design-prompt.d.ts +28 -0
  254. package/dist/strategy-design-prompt.d.ts.map +1 -0
  255. package/dist/strategy-design-prompt.js +108 -0
  256. package/dist/strategy-design-prompt.js.map +1 -0
  257. package/dist/strategy-design-schema.d.ts +767 -0
  258. package/dist/strategy-design-schema.d.ts.map +1 -0
  259. package/dist/strategy-design-schema.js +126 -0
  260. package/dist/strategy-design-schema.js.map +1 -0
  261. package/dist/strategy-design.d.ts +69 -0
  262. package/dist/strategy-design.d.ts.map +1 -0
  263. package/dist/strategy-design.js +411 -0
  264. package/dist/strategy-design.js.map +1 -0
  265. package/dist/strategy-gating.d.ts +31 -0
  266. package/dist/strategy-gating.d.ts.map +1 -0
  267. package/dist/strategy-gating.js +276 -0
  268. package/dist/strategy-gating.js.map +1 -0
  269. package/dist/team-prompt-builder.d.ts +47 -0
  270. package/dist/team-prompt-builder.d.ts.map +1 -0
  271. package/dist/team-prompt-builder.js +362 -0
  272. package/dist/team-prompt-builder.js.map +1 -0
  273. package/dist/trace-engine.d.ts +40 -0
  274. package/dist/trace-engine.d.ts.map +1 -0
  275. package/dist/trace-engine.js +344 -0
  276. package/dist/trace-engine.js.map +1 -0
  277. package/dist/types.d.ts +612 -0
  278. package/dist/types.d.ts.map +1 -0
  279. package/dist/types.js +9 -0
  280. package/dist/types.js.map +1 -0
  281. package/dist/unit-session-lifecycle.d.ts +78 -0
  282. package/dist/unit-session-lifecycle.d.ts.map +1 -0
  283. package/dist/unit-session-lifecycle.js +141 -0
  284. package/dist/unit-session-lifecycle.js.map +1 -0
  285. package/dist/unit-session.d.ts +30 -0
  286. package/dist/unit-session.d.ts.map +1 -0
  287. package/dist/unit-session.js +370 -0
  288. package/dist/unit-session.js.map +1 -0
  289. package/dist/watchdogs.d.ts +33 -0
  290. package/dist/watchdogs.d.ts.map +1 -0
  291. package/dist/watchdogs.js +170 -0
  292. package/dist/watchdogs.js.map +1 -0
  293. package/dist/work-unit-scheduler.d.ts +34 -0
  294. package/dist/work-unit-scheduler.d.ts.map +1 -0
  295. package/dist/work-unit-scheduler.js +91 -0
  296. package/dist/work-unit-scheduler.js.map +1 -0
  297. package/dist/workflow-transition.d.ts +90 -0
  298. package/dist/workflow-transition.d.ts.map +1 -0
  299. package/dist/workflow-transition.js +340 -0
  300. package/dist/workflow-transition.js.map +1 -0
  301. package/package.json +65 -0
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Factory execution -- barrel re-export.
3
+ *
4
+ * The implementation has been split into focused modules:
5
+ * - builder-spawner.ts -- builder process spawning, env setup, stream handling
6
+ * - builder-completion.ts -- builder completion handling, execution cycle orchestration
7
+ * - execution-target.ts -- BuilderExecutionTarget (TriggerExecutionTarget impl)
8
+ * - work-unit-scheduler.ts -- DAG-aware work unit readiness, dependency maps
9
+ *
10
+ * This file preserves the original import path for consumers (index.ts, tests).
11
+ */
12
+ // Work unit scheduling
13
+ export { findReadyWorkUnits } from './work-unit-scheduler.js';
14
+ // Builder spawning
15
+ export { spawnBuilder, transitionWorkUnitStatus, DEFAULT_MAX_ITERATIONS, LOG_PREFIX, lastGateOutputByWorkUnit } from './builder-spawner.js';
16
+ // Builder completion & execution cycle
17
+ export { handleBuilderCompletion, runExecutionCycle } from './builder-completion.js';
18
+ // Execution target
19
+ export { BuilderExecutionTarget, getBuilderTarget } from './execution-target.js';
20
+ //# sourceMappingURL=execution.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution.js","sourceRoot":"","sources":["../src/execution.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,uBAAuB;AACvB,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAG9D,mBAAmB;AACnB,OAAO,EAAE,YAAY,EAAE,wBAAwB,EAAE,sBAAsB,EAAE,UAAU,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAE5I,uCAAuC;AACvC,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAErF,mBAAmB;AACnB,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * FactoryEngine -- ExecutionEngine adapter for the factory orchestrator.
3
+ *
4
+ * Wraps the existing factory modules (config, instance-lifecycle, completion,
5
+ * crash-recovery, queries/shared) behind the ExecutionEngine interface so that
6
+ * the unified daemon process shell can manage the factory engine alongside
7
+ * other engines (strategy, etc.) through a single contract.
8
+ *
9
+ * Lifecycle sequence (driven by the process shell):
10
+ * 1. init(config) -- validate config, init API client, validate auth
11
+ * 2. recoverFromCrash() -- reconcile orphaned worktrees, stale sessions
12
+ * 3. start() -- begin the 30s poll loop
13
+ * ... running ...
14
+ * 4. stop() -- stop accepting new work
15
+ * 5. shutdown() -- kill builders, WIP commit worktrees, drain
16
+ */
17
+ import type { ExecutionEngine, EngineHealth, ResourceUsage, BaseConfig } from '@telora/daemon-core';
18
+ import type { ResourceGovernor } from '@telora/daemon-core';
19
+ /**
20
+ * ExecutionEngine adapter for the Telora factory orchestrator.
21
+ *
22
+ * All engine-specific behavior is delegated to existing factory modules.
23
+ * This class is a thin wrapper that maps the ExecutionEngine lifecycle
24
+ * methods onto those modules.
25
+ */
26
+ export declare class FactoryEngine implements ExecutionEngine {
27
+ readonly name = "factory";
28
+ /** Factory configuration, set during init(). */
29
+ private config;
30
+ /** Optional global resource governor for cross-engine concurrency control. */
31
+ private governor;
32
+ /** Periodic intervals to clear on stop(). */
33
+ private intervals;
34
+ /**
35
+ * Initialize the engine with its configuration.
36
+ *
37
+ * Validates config, initializes the API client, and verifies tracker
38
+ * authentication before any other engine method is called.
39
+ */
40
+ init(config: BaseConfig & Record<string, unknown>): Promise<void>;
41
+ /**
42
+ * Set the optional resource governor for global concurrency control.
43
+ *
44
+ * When set, all Claude Code process spawns within the factory acquire a
45
+ * slot from the governor before spawning and release it on exit. This
46
+ * provides cross-engine concurrency limiting in addition to the factory's
47
+ * own maxConcurrentInstances check.
48
+ */
49
+ setGovernor(gov: ResourceGovernor): void;
50
+ /**
51
+ * Recover from a previous crash.
52
+ *
53
+ * Delegates to the crash-recovery module which scans for orphaned
54
+ * worktrees, resets stale sessions, and pauses stuck instances.
55
+ */
56
+ recoverFromCrash(): Promise<void>;
57
+ /**
58
+ * Start the factory's polling loop.
59
+ *
60
+ * After this call the engine actively discovers and processes factory
61
+ * instances on a 30-second interval. Also runs startup log pruning and
62
+ * schedules periodic hourly pruning.
63
+ */
64
+ start(): Promise<void>;
65
+ /**
66
+ * Stop accepting new work.
67
+ *
68
+ * Sets the shutdown flag (poll loop becomes a no-op), clears the
69
+ * poll interval, and stops periodic tasks. In-progress instances
70
+ * continue running.
71
+ */
72
+ stop(): void;
73
+ /**
74
+ * Graceful shutdown with full cleanup.
75
+ *
76
+ * 1. Kill active builder child processes (SIGTERM).
77
+ * 2. WIP commit uncommitted changes in instance worktrees.
78
+ * 3. Bail out if the 10-second timeout is exceeded.
79
+ *
80
+ * The engine is inert after this method returns.
81
+ */
82
+ shutdown(): Promise<void>;
83
+ /**
84
+ * Return a snapshot of the engine's health.
85
+ *
86
+ * Status is 'healthy' when there are active instances, 'degraded' when
87
+ * idle (no work items), and never 'unhealthy' under normal conditions
88
+ * (unhealthy would be set by an external monitor if the engine fails to
89
+ * respond).
90
+ */
91
+ healthCheck(): EngineHealth;
92
+ /**
93
+ * Return a snapshot of the engine's resource usage.
94
+ *
95
+ * - `activeClaudeProcesses`: total running builder sessions across all instances.
96
+ * - `activeWorktrees`: instances that have an allocated worktree path.
97
+ */
98
+ getResourceUsage(): ResourceUsage;
99
+ }
100
+ //# sourceMappingURL=factory-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory-engine.d.ts","sourceRoot":"","sources":["../src/factory-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACpG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AA2B5D;;;;;;GAMG;AACH,qBAAa,aAAc,YAAW,eAAe;IACnD,QAAQ,CAAC,IAAI,aAAa;IAE1B,gDAAgD;IAChD,OAAO,CAAC,MAAM,CAA8B;IAE5C,8EAA8E;IAC9E,OAAO,CAAC,QAAQ,CAAiC;IAEjD,6CAA6C;IAC7C,OAAO,CAAC,SAAS,CAAwC;IAMzD;;;;;OAKG;IACG,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAavE;;;;;;;OAOG;IACH,WAAW,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI;IASxC;;;;;OAKG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IAWvC;;;;;;OAMG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAiC5B;;;;;;OAMG;IACH,IAAI,IAAI,IAAI;IAaZ;;;;;;;;OAQG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IA8C/B;;;;;;;OAOG;IACH,WAAW,IAAI,YAAY;IAqB3B;;;;;OAKG;IACH,gBAAgB,IAAI,aAAa;CAqBlC"}
@@ -0,0 +1,243 @@
1
+ /**
2
+ * FactoryEngine -- ExecutionEngine adapter for the factory orchestrator.
3
+ *
4
+ * Wraps the existing factory modules (config, instance-lifecycle, completion,
5
+ * crash-recovery, queries/shared) behind the ExecutionEngine interface so that
6
+ * the unified daemon process shell can manage the factory engine alongside
7
+ * other engines (strategy, etc.) through a single contract.
8
+ *
9
+ * Lifecycle sequence (driven by the process shell):
10
+ * 1. init(config) -- validate config, init API client, validate auth
11
+ * 2. recoverFromCrash() -- reconcile orphaned worktrees, stale sessions
12
+ * 3. start() -- begin the 30s poll loop
13
+ * ... running ...
14
+ * 4. stop() -- stop accepting new work
15
+ * 5. shutdown() -- kill builders, WIP commit worktrees, drain
16
+ */
17
+ import { safeInterval } from '@telora/daemon-core';
18
+ import { validateConfig } from './config.js';
19
+ import { initApiClient, validateTrackerAuth } from './queries/shared.js';
20
+ import { recoverFromCrash } from './crash-recovery.js';
21
+ import { startPollLoop, stopPollLoop, getActiveInstances, setShuttingDown, setFactoryGovernor, } from './instance-lifecycle.js';
22
+ import { commitWipOnShutdown } from './completion.js';
23
+ import { pruneFactoryLogs, createFactoryLogManagerDeps } from './log-manager.js';
24
+ // ---------------------------------------------------------------------------
25
+ // Shutdown constants
26
+ // ---------------------------------------------------------------------------
27
+ /** Maximum time (ms) allowed for the graceful shutdown sequence. */
28
+ const SHUTDOWN_TIMEOUT_MS = 10_000;
29
+ // ---------------------------------------------------------------------------
30
+ // FactoryEngine
31
+ // ---------------------------------------------------------------------------
32
+ /**
33
+ * ExecutionEngine adapter for the Telora factory orchestrator.
34
+ *
35
+ * All engine-specific behavior is delegated to existing factory modules.
36
+ * This class is a thin wrapper that maps the ExecutionEngine lifecycle
37
+ * methods onto those modules.
38
+ */
39
+ export class FactoryEngine {
40
+ name = 'factory';
41
+ /** Factory configuration, set during init(). */
42
+ config = null;
43
+ /** Optional global resource governor for cross-engine concurrency control. */
44
+ governor = null;
45
+ /** Periodic intervals to clear on stop(). */
46
+ intervals = [];
47
+ // -------------------------------------------------------------------------
48
+ // Lifecycle: init
49
+ // -------------------------------------------------------------------------
50
+ /**
51
+ * Initialize the engine with its configuration.
52
+ *
53
+ * Validates config, initializes the API client, and verifies tracker
54
+ * authentication before any other engine method is called.
55
+ */
56
+ async init(config) {
57
+ const factoryConfig = config;
58
+ this.config = factoryConfig;
59
+ validateConfig(factoryConfig);
60
+ initApiClient(factoryConfig);
61
+ await validateTrackerAuth();
62
+ }
63
+ // -------------------------------------------------------------------------
64
+ // Resource governor
65
+ // -------------------------------------------------------------------------
66
+ /**
67
+ * Set the optional resource governor for global concurrency control.
68
+ *
69
+ * When set, all Claude Code process spawns within the factory acquire a
70
+ * slot from the governor before spawning and release it on exit. This
71
+ * provides cross-engine concurrency limiting in addition to the factory's
72
+ * own maxConcurrentInstances check.
73
+ */
74
+ setGovernor(gov) {
75
+ this.governor = gov;
76
+ setFactoryGovernor(gov);
77
+ }
78
+ // -------------------------------------------------------------------------
79
+ // Lifecycle: crash recovery
80
+ // -------------------------------------------------------------------------
81
+ /**
82
+ * Recover from a previous crash.
83
+ *
84
+ * Delegates to the crash-recovery module which scans for orphaned
85
+ * worktrees, resets stale sessions, and pauses stuck instances.
86
+ */
87
+ async recoverFromCrash() {
88
+ if (!this.config) {
89
+ throw new Error('FactoryEngine.recoverFromCrash() called before init()');
90
+ }
91
+ await recoverFromCrash(this.config);
92
+ }
93
+ // -------------------------------------------------------------------------
94
+ // Lifecycle: start
95
+ // -------------------------------------------------------------------------
96
+ /**
97
+ * Start the factory's polling loop.
98
+ *
99
+ * After this call the engine actively discovers and processes factory
100
+ * instances on a 30-second interval. Also runs startup log pruning and
101
+ * schedules periodic hourly pruning.
102
+ */
103
+ async start() {
104
+ if (!this.config) {
105
+ throw new Error('FactoryEngine.start() called before init()');
106
+ }
107
+ // Escalation-aware log preservation deps
108
+ const logDeps = createFactoryLogManagerDeps(this.config);
109
+ // Startup log pruning (non-fatal)
110
+ try {
111
+ await pruneFactoryLogs(this.config, logDeps);
112
+ }
113
+ catch (err) {
114
+ console.warn('[factory-engine] Startup log pruning failed (non-fatal):', err instanceof Error ? err.message : String(err));
115
+ }
116
+ startPollLoop(this.config);
117
+ // Periodic log pruning (hourly)
118
+ const config = this.config;
119
+ this.intervals.push(safeInterval(async () => {
120
+ await pruneFactoryLogs(config, logDeps);
121
+ }, 3_600_000, 'factory-log-prune'));
122
+ }
123
+ // -------------------------------------------------------------------------
124
+ // Lifecycle: stop
125
+ // -------------------------------------------------------------------------
126
+ /**
127
+ * Stop accepting new work.
128
+ *
129
+ * Sets the shutdown flag (poll loop becomes a no-op), clears the
130
+ * poll interval, and stops periodic tasks. In-progress instances
131
+ * continue running.
132
+ */
133
+ stop() {
134
+ for (const interval of this.intervals) {
135
+ clearInterval(interval);
136
+ }
137
+ this.intervals = [];
138
+ setShuttingDown();
139
+ stopPollLoop();
140
+ }
141
+ // -------------------------------------------------------------------------
142
+ // Lifecycle: shutdown
143
+ // -------------------------------------------------------------------------
144
+ /**
145
+ * Graceful shutdown with full cleanup.
146
+ *
147
+ * 1. Kill active builder child processes (SIGTERM).
148
+ * 2. WIP commit uncommitted changes in instance worktrees.
149
+ * 3. Bail out if the 10-second timeout is exceeded.
150
+ *
151
+ * The engine is inert after this method returns.
152
+ */
153
+ async shutdown() {
154
+ const shutdownStart = Date.now();
155
+ const instances = getActiveInstances();
156
+ for (const [instanceId, state] of instances) {
157
+ // Kill active builder child processes (legacy solo mode)
158
+ for (const [, builder] of state.activeBuilderSessions) {
159
+ try {
160
+ process.kill(builder.pid, 'SIGTERM');
161
+ console.log(`[factory-engine] Sent SIGTERM to builder pid ${builder.pid} ` +
162
+ `(work unit ${builder.workUnitId})`);
163
+ }
164
+ catch {
165
+ // Process may already be dead
166
+ }
167
+ }
168
+ // Terminate execution unit sessions (DAG-aware scheduler model)
169
+ const { terminateAllUnits } = await import('./unit-session-lifecycle.js');
170
+ terminateAllUnits(state);
171
+ // WIP commit any uncommitted changes in the worktree
172
+ if (state.worktreePath) {
173
+ try {
174
+ await commitWipOnShutdown(instanceId, state.worktreePath, 'graceful-shutdown');
175
+ }
176
+ catch (err) {
177
+ console.error(`[factory-engine] Failed to WIP commit for instance ${instanceId}: ` +
178
+ `${err instanceof Error ? err.message : String(err)}`);
179
+ }
180
+ }
181
+ // Bail out if we are taking too long
182
+ if (Date.now() - shutdownStart > SHUTDOWN_TIMEOUT_MS) {
183
+ console.warn('[factory-engine] Shutdown timeout reached, forcing exit');
184
+ break;
185
+ }
186
+ }
187
+ }
188
+ // -------------------------------------------------------------------------
189
+ // Health check
190
+ // -------------------------------------------------------------------------
191
+ /**
192
+ * Return a snapshot of the engine's health.
193
+ *
194
+ * Status is 'healthy' when there are active instances, 'degraded' when
195
+ * idle (no work items), and never 'unhealthy' under normal conditions
196
+ * (unhealthy would be set by an external monitor if the engine fails to
197
+ * respond).
198
+ */
199
+ healthCheck() {
200
+ const instances = getActiveInstances();
201
+ const instanceDetails = {};
202
+ for (const [instanceId, state] of instances) {
203
+ instanceDetails[instanceId] = state.status;
204
+ }
205
+ return {
206
+ status: instances.size > 0 ? 'healthy' : 'degraded',
207
+ activeWorkItems: instances.size,
208
+ details: {
209
+ instances: instanceDetails,
210
+ },
211
+ };
212
+ }
213
+ // -------------------------------------------------------------------------
214
+ // Resource usage
215
+ // -------------------------------------------------------------------------
216
+ /**
217
+ * Return a snapshot of the engine's resource usage.
218
+ *
219
+ * - `activeClaudeProcesses`: total running builder sessions across all instances.
220
+ * - `activeWorktrees`: instances that have an allocated worktree path.
221
+ */
222
+ getResourceUsage() {
223
+ const instances = getActiveInstances();
224
+ let activeClaudeProcesses = 0;
225
+ let activeWorktrees = 0;
226
+ for (const [, state] of instances) {
227
+ activeClaudeProcesses += state.activeBuilderSessions.size;
228
+ // Count execution unit sessions with active PIDs
229
+ for (const unit of state.executionUnits.values()) {
230
+ if (unit.pid !== null)
231
+ activeClaudeProcesses++;
232
+ }
233
+ if (state.worktreePath) {
234
+ activeWorktrees++;
235
+ }
236
+ }
237
+ return {
238
+ activeClaudeProcesses,
239
+ activeWorktrees,
240
+ };
241
+ }
242
+ }
243
+ //# sourceMappingURL=factory-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory-engine.js","sourceRoot":"","sources":["../src/factory-engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAEnD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,mBAAmB,EAAE,MAAM,qBAA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jD,CAAC;YACD,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;gBACvB,eAAe,EAAE,CAAC;YACpB,CAAC;QACH,CAAC;QAED,OAAO;YACL,qBAAqB;YACrB,eAAe;SAChB,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Gap analysis for factory re-planning.
3
+ *
4
+ * Detects gaps in completed work by analyzing gate results and completion
5
+ * evaluations. Provides:
6
+ * - Verification gap filtering (strips test/build verification concerns)
7
+ * - Prior cycle context formatting for re-planning prompts
8
+ * - Strategy matching for assigning re-planned work units
9
+ */
10
+ import type { FactoryCycleEvaluation, FactoryWorkUnit } from './types.js';
11
+ import type { PersistedStrategy } from './strategy-design.js';
12
+ /**
13
+ * Filter completion gate gaps to only include those describing absent
14
+ * functional capabilities. Strips verification-related gaps (test execution,
15
+ * build confirmation, etc.) that are not spec requirements.
16
+ */
17
+ export declare function filterFunctionalGaps(gaps: Array<{
18
+ area: string;
19
+ description: string;
20
+ severity: string;
21
+ }>): Array<{
22
+ area: string;
23
+ description: string;
24
+ severity: string;
25
+ }>;
26
+ /**
27
+ * Format prior cycle evaluations and completed work units into a concise
28
+ * markdown string for injection into the re-planning prompt.
29
+ *
30
+ * Rules:
31
+ * - Work unit descriptions truncated to ~100 chars to save context
32
+ * - Only completed work units included (not failed/pending)
33
+ * - Gap descriptions kept in full (they are the signal for what is missing)
34
+ * - Total output capped at MAX_PRIOR_CONTEXT_CHARS
35
+ */
36
+ export declare function formatPriorCycleContext(evaluations: FactoryCycleEvaluation[], completedWorkUnits: FactoryWorkUnit[]): string;
37
+ /**
38
+ * Best-effort matching of a new work unit to an existing strategy based on
39
+ * text similarity between the work unit title/description and strategy
40
+ * name/description. Returns the most relevant strategy ID or undefined.
41
+ */
42
+ export declare function matchWorkUnitToStrategy(title: string, description: string, strategies: PersistedStrategy[]): string | undefined;
43
+ //# sourceMappingURL=gap-detection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gap-detection.d.ts","sourceRoot":"","sources":["../src/gap-detection.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EACV,sBAAsB,EACtB,eAAe,EAChB,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAyC9D;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,GACnE,KAAK,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC,CAUhE;AAMD;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CACrC,WAAW,EAAE,sBAAsB,EAAE,EACrC,kBAAkB,EAAE,eAAe,EAAE,GACpC,MAAM,CA6DR;AAMD;;;;GAIG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,MAAM,EACnB,UAAU,EAAE,iBAAiB,EAAE,GAC9B,MAAM,GAAG,SAAS,CAyBpB"}
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Gap analysis for factory re-planning.
3
+ *
4
+ * Detects gaps in completed work by analyzing gate results and completion
5
+ * evaluations. Provides:
6
+ * - Verification gap filtering (strips test/build verification concerns)
7
+ * - Prior cycle context formatting for re-planning prompts
8
+ * - Strategy matching for assigning re-planned work units
9
+ */
10
+ // ============================================================================
11
+ // Constants
12
+ // ============================================================================
13
+ /** Maximum character length for the prior cycle context to keep prompt budget. */
14
+ const MAX_PRIOR_CONTEXT_CHARS = 4_000;
15
+ /** Maximum character length for truncated work unit descriptions. */
16
+ const MAX_WU_DESC_CHARS = 100;
17
+ /** Log prefix for this module. */
18
+ const LOG_PREFIX = '[replanning]';
19
+ // ============================================================================
20
+ // Gap filtering (strip verification-only gaps before re-planning)
21
+ // ============================================================================
22
+ /**
23
+ * Patterns that indicate a gap is about test execution, build verification,
24
+ * or command execution rather than a missing functional capability.
25
+ */
26
+ const VERIFICATION_GAP_PATTERNS = [
27
+ /\bverif(y|ied|ication)\b.*\b(test|build|lint|typecheck|npm)\b/i,
28
+ /\b(run|execute|confirm)\b.*\b(test|build|lint|typecheck|npm)\b/i,
29
+ /\bnpm\s+(test|run\s+(build|lint|typecheck))\b/i,
30
+ /\btest\s+suite\s+(execution|run|pass)/i,
31
+ /\bbuild\s+(succeed|pass|valid)/i,
32
+ /\bensure\b.*\b(test|build|lint)\b.*\b(pass|succeed|run)/i,
33
+ ];
34
+ /**
35
+ * Returns true if a gap describes a verification/test-execution concern
36
+ * rather than an absent functional capability.
37
+ */
38
+ function isVerificationGap(gap) {
39
+ const text = `${gap.area} ${gap.description}`;
40
+ return VERIFICATION_GAP_PATTERNS.some((pattern) => pattern.test(text));
41
+ }
42
+ /**
43
+ * Filter completion gate gaps to only include those describing absent
44
+ * functional capabilities. Strips verification-related gaps (test execution,
45
+ * build confirmation, etc.) that are not spec requirements.
46
+ */
47
+ export function filterFunctionalGaps(gaps) {
48
+ return gaps.filter((gap) => {
49
+ if (isVerificationGap(gap)) {
50
+ console.log(`${LOG_PREFIX} Filtered verification gap from re-planning context: ${gap.area}`);
51
+ return false;
52
+ }
53
+ return true;
54
+ });
55
+ }
56
+ // ============================================================================
57
+ // Prior cycle context formatter (TEL-2)
58
+ // ============================================================================
59
+ /**
60
+ * Format prior cycle evaluations and completed work units into a concise
61
+ * markdown string for injection into the re-planning prompt.
62
+ *
63
+ * Rules:
64
+ * - Work unit descriptions truncated to ~100 chars to save context
65
+ * - Only completed work units included (not failed/pending)
66
+ * - Gap descriptions kept in full (they are the signal for what is missing)
67
+ * - Total output capped at MAX_PRIOR_CONTEXT_CHARS
68
+ */
69
+ export function formatPriorCycleContext(evaluations, completedWorkUnits) {
70
+ if (evaluations.length === 0) {
71
+ return '';
72
+ }
73
+ const parts = ['## Prior Cycle History', ''];
74
+ for (const evaluation of evaluations) {
75
+ parts.push(`### Cycle ${evaluation.cycleNumber}`);
76
+ parts.push(`Evaluation: ${evaluation.passed ? 'PASSED' : 'FAILED'} ` +
77
+ `(confidence: ${evaluation.confidence})`);
78
+ parts.push(`Summary: ${evaluation.summary}`);
79
+ // Filter to functional gaps only (strip verification/test-execution gaps)
80
+ const functionalGaps = filterFunctionalGaps(evaluation.gaps);
81
+ // Critical gaps
82
+ const criticalGaps = functionalGaps.filter((g) => g.severity === 'critical');
83
+ if (criticalGaps.length > 0) {
84
+ parts.push('Critical gaps found:');
85
+ for (const gap of criticalGaps) {
86
+ parts.push(`- ${gap.area}: ${gap.description}`);
87
+ }
88
+ }
89
+ // Important gaps (brief)
90
+ const importantGaps = functionalGaps.filter((g) => g.severity === 'important');
91
+ if (importantGaps.length > 0) {
92
+ parts.push(`Important gaps (${importantGaps.length}): ${importantGaps.map((g) => g.area).join(', ')}`);
93
+ }
94
+ // Work units completed in this cycle
95
+ const cycleUnits = completedWorkUnits.filter((wu) => wu.cycleNumber === evaluation.cycleNumber);
96
+ if (cycleUnits.length > 0) {
97
+ parts.push(`Work completed (${cycleUnits.length} units):`);
98
+ for (const wu of cycleUnits) {
99
+ const desc = wu.description
100
+ ? wu.description.length > MAX_WU_DESC_CHARS
101
+ ? wu.description.slice(0, MAX_WU_DESC_CHARS) + '...'
102
+ : wu.description
103
+ : 'No description';
104
+ parts.push(`- ${wu.title}: ${desc}`);
105
+ }
106
+ }
107
+ parts.push('');
108
+ }
109
+ let formatted = parts.join('\n');
110
+ // Truncate if over budget
111
+ if (formatted.length > MAX_PRIOR_CONTEXT_CHARS) {
112
+ const truncationNote = '\n\n[Prior cycle context truncated due to size constraints]';
113
+ formatted = formatted.slice(0, MAX_PRIOR_CONTEXT_CHARS - truncationNote.length) + truncationNote;
114
+ }
115
+ return formatted;
116
+ }
117
+ // ============================================================================
118
+ // Strategy matching for re-planned work units
119
+ // ============================================================================
120
+ /**
121
+ * Best-effort matching of a new work unit to an existing strategy based on
122
+ * text similarity between the work unit title/description and strategy
123
+ * name/description. Returns the most relevant strategy ID or undefined.
124
+ */
125
+ export function matchWorkUnitToStrategy(title, description, strategies) {
126
+ if (strategies.length === 0)
127
+ return undefined;
128
+ const text = `${title} ${description}`.toLowerCase();
129
+ let bestScore = 0;
130
+ let bestId;
131
+ for (const strategy of strategies) {
132
+ const keywords = [
133
+ strategy.name.toLowerCase(),
134
+ ...(strategy.description?.toLowerCase().split(/\s+/) ?? []),
135
+ ];
136
+ let score = 0;
137
+ for (const kw of keywords) {
138
+ if (kw.length >= 3 && text.includes(kw)) {
139
+ score += kw.length;
140
+ }
141
+ }
142
+ if (score > bestScore) {
143
+ bestScore = score;
144
+ bestId = strategy.id;
145
+ }
146
+ }
147
+ return bestId;
148
+ }
149
+ //# sourceMappingURL=gap-detection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gap-detection.js","sourceRoot":"","sources":["../src/gap-detection.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAQH,+EAA+E;AAC/E,YAAY;AACZ,+EAA+E;AAE/E,kFAAkF;AAClF,MAAM,uBAAuB,GAAG,KAAK,CAAC;AAEtC,qEAAqE;AACrE,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAE9B,kCAAkC;AAClC,MAAM,UAAU,GAAG,cAAc,CAAC;AAElC,+EAA+E;AAC/E,kEAAkE;AAClE,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,yBAAyB,GAAG;IAChC,gEAAgE;IAChE,iEAAiE;IACjE,gDAAgD;IAChD,wCAAwC;IACxC,iCAAiC;IACjC,0DAA0D;CAC3D,CAAC;AAEF;;;GAGG;AACH,SAAS,iBAAiB,CAAC,GAA0C;IACnE,MAAM,IAAI,GAAG,GAAG,GAAG,CAAC,IAAI,IAAI,GAAG,CAAC,WAAW,EAAE,CAAC;IAC9C,OAAO,yBAAyB,CAAC,IAAI,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AAE,CAAC;YAC1B,IAAI,EAAE,CAAC,MAAM,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC;gBACxC,KAAK,IAAI,EAAE,CAAC,MAAM,CAAC;YACrB,CAAC;QACH,CAAC;QACD,IAAI,KAAK,GAAG,SAAS,EAAE,CAAC;YACtB,SAAS,GAAG,KAAK,CAAC;YAClB,MAAM,GAAG,QAAQ,CAAC,EAAE,CAAC;QACvB,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Gate context formatter.
3
+ *
4
+ * Builds a human-readable summary of which gate layers were enabled on a
5
+ * blueprint and what they validate. Used to give AI reviewers and planners
6
+ * context about which validation dimensions the gate system already handles,
7
+ * so they do not flag test coverage, type safety, or E2E behavior as gaps.
8
+ *
9
+ * This module has no dependencies other than types, so it can be safely
10
+ * imported by any prompt builder without pulling in the full gate stack.
11
+ */
12
+ import type { FactoryBlueprint } from './types.js';
13
+ /**
14
+ * Build a human-readable summary of which gates were enabled on this blueprint
15
+ * and what they validated.
16
+ *
17
+ * Called only when all strategy-level gates have already passed, so every
18
+ * gate listed here is known to have succeeded before the review runs.
19
+ *
20
+ * Returns an empty string if no gates are enabled (caller should skip the section).
21
+ */
22
+ export declare function formatGateContext(blueprint: FactoryBlueprint): string;
23
+ //# sourceMappingURL=gate-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gate-context.d.ts","sourceRoot":"","sources":["../src/gate-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,gBAAgB,GAAG,MAAM,CA+CrE"}