@yuaone/core 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +50 -6
  2. package/dist/agent-loop.d.ts +36 -0
  3. package/dist/agent-loop.d.ts.map +1 -1
  4. package/dist/agent-loop.js +504 -97
  5. package/dist/agent-loop.js.map +1 -1
  6. package/dist/code-indexer.d.ts +50 -0
  7. package/dist/code-indexer.d.ts.map +1 -0
  8. package/dist/code-indexer.js +199 -0
  9. package/dist/code-indexer.js.map +1 -0
  10. package/dist/failure-recovery.d.ts +15 -2
  11. package/dist/failure-recovery.d.ts.map +1 -1
  12. package/dist/failure-recovery.js +53 -2
  13. package/dist/failure-recovery.js.map +1 -1
  14. package/dist/index.d.ts +6 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +6 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/llm-client.d.ts +11 -2
  19. package/dist/llm-client.d.ts.map +1 -1
  20. package/dist/llm-client.js +23 -8
  21. package/dist/llm-client.js.map +1 -1
  22. package/dist/planner/index.d.ts +9 -0
  23. package/dist/planner/index.d.ts.map +1 -0
  24. package/dist/planner/index.js +5 -0
  25. package/dist/planner/index.js.map +1 -0
  26. package/dist/planner/milestone-checker.d.ts +48 -0
  27. package/dist/planner/milestone-checker.d.ts.map +1 -0
  28. package/dist/planner/milestone-checker.js +113 -0
  29. package/dist/planner/milestone-checker.js.map +1 -0
  30. package/dist/planner/plan-evaluator.d.ts +35 -0
  31. package/dist/planner/plan-evaluator.d.ts.map +1 -0
  32. package/dist/planner/plan-evaluator.js +92 -0
  33. package/dist/planner/plan-evaluator.js.map +1 -0
  34. package/dist/planner/replanning-engine.d.ts +37 -0
  35. package/dist/planner/replanning-engine.d.ts.map +1 -0
  36. package/dist/planner/replanning-engine.js +130 -0
  37. package/dist/planner/replanning-engine.js.map +1 -0
  38. package/dist/planner/risk-estimator.d.ts +44 -0
  39. package/dist/planner/risk-estimator.d.ts.map +1 -0
  40. package/dist/planner/risk-estimator.js +108 -0
  41. package/dist/planner/risk-estimator.js.map +1 -0
  42. package/dist/world-model/index.d.ts +8 -0
  43. package/dist/world-model/index.d.ts.map +1 -0
  44. package/dist/world-model/index.js +5 -0
  45. package/dist/world-model/index.js.map +1 -0
  46. package/dist/world-model/simulation-engine.d.ts +58 -0
  47. package/dist/world-model/simulation-engine.d.ts.map +1 -0
  48. package/dist/world-model/simulation-engine.js +191 -0
  49. package/dist/world-model/simulation-engine.js.map +1 -0
  50. package/dist/world-model/state-store.d.ts +149 -0
  51. package/dist/world-model/state-store.d.ts.map +1 -0
  52. package/dist/world-model/state-store.js +379 -0
  53. package/dist/world-model/state-store.js.map +1 -0
  54. package/dist/world-model/state-updater.d.ts +35 -0
  55. package/dist/world-model/state-updater.d.ts.map +1 -0
  56. package/dist/world-model/state-updater.js +131 -0
  57. package/dist/world-model/state-updater.js.map +1 -0
  58. package/dist/world-model/transition-model.d.ts +54 -0
  59. package/dist/world-model/transition-model.d.ts.map +1 -0
  60. package/dist/world-model/transition-model.js +240 -0
  61. package/dist/world-model/transition-model.js.map +1 -0
  62. package/package.json +1 -1
@@ -0,0 +1,130 @@
1
+ /**
2
+ * @module planner/replanning-engine
3
+ * @description Proactive replanning engine — evaluates plan health mid-execution
4
+ * and triggers partial or full replanning when deviations are detected.
5
+ */
6
+ // ─── ReplanningEngine ───
7
+ export class ReplanningEngine {
8
+ planner;
9
+ planEvaluator;
10
+ riskEstimator;
11
+ milestoneChecker;
12
+ constructor(planner, planEvaluator, riskEstimator, milestoneChecker) {
13
+ this.planner = planner;
14
+ this.planEvaluator = planEvaluator;
15
+ this.riskEstimator = riskEstimator;
16
+ this.milestoneChecker = milestoneChecker;
17
+ }
18
+ async evaluate(plan, currentState, completedTaskIds, toolResults, tokensUsed, tokenBudget, changedFiles, currentIteration, activeMilestones, llmClient) {
19
+ const remainingTasks = plan.tactical.filter(t => !completedTaskIds.includes(t.id));
20
+ const completedTasks = plan.tactical.filter(t => completedTaskIds.includes(t.id));
21
+ // 1. Evaluate plan health
22
+ const health = this.planEvaluator.evaluate(plan, completedTaskIds, toolResults, tokensUsed, tokenBudget);
23
+ // 2. Estimate risk
24
+ const risk = await this.riskEstimator.estimate(currentState, remainingTasks, completedTasks, changedFiles, tokensUsed, tokenBudget);
25
+ // 3. Check milestones
26
+ const milestoneStatus = this.milestoneChecker.check(activeMilestones, completedTaskIds, currentIteration);
27
+ // 4. Decide whether to replan
28
+ const decision = this.shouldTrigger(health, risk, milestoneStatus);
29
+ if (!decision.shouldReplan) {
30
+ return { triggered: false, decision, message: "Plan on track" };
31
+ }
32
+ // 5. Execute replan
33
+ try {
34
+ const result = await this.executeReplan(plan, decision, currentState, llmClient);
35
+ const message = `Proactive replan triggered (${decision.scope}): ${decision.trigger}`;
36
+ return { triggered: true, decision, modifiedTasks: result, message };
37
+ }
38
+ catch (err) {
39
+ return {
40
+ triggered: false,
41
+ decision,
42
+ message: `Replan attempted but failed: ${String(err)}`,
43
+ };
44
+ }
45
+ }
46
+ shouldTrigger(health, risk, milestoneStatus) {
47
+ // Critical: abort conditions
48
+ if (health.recommendation === "abort") {
49
+ return {
50
+ shouldReplan: true,
51
+ scope: "strategic",
52
+ trigger: "Plan health critical",
53
+ urgency: "critical",
54
+ reasoning: `Health score ${health.score}/100, recommendation: abort`,
55
+ };
56
+ }
57
+ // High risk → strategic replan
58
+ if (risk.overall >= 85) {
59
+ return {
60
+ shouldReplan: true,
61
+ scope: "strategic",
62
+ trigger: `Risk score ${risk.overall}/100`,
63
+ urgency: "critical",
64
+ reasoning: risk.factors.join("; "),
65
+ };
66
+ }
67
+ // Medium-high risk → tactical replan
68
+ if (risk.overall >= 70) {
69
+ return {
70
+ shouldReplan: true,
71
+ scope: "tactical",
72
+ trigger: `Elevated risk: ${risk.overall}/100`,
73
+ urgency: "high",
74
+ reasoning: risk.factors.join("; "),
75
+ };
76
+ }
77
+ // Major health issues → major replan
78
+ if (health.recommendation === "replan_major") {
79
+ return {
80
+ shouldReplan: true,
81
+ scope: "tactical",
82
+ trigger: "Plan health deteriorated",
83
+ urgency: "high",
84
+ reasoning: health.deviations.map(d => d.description).join("; "),
85
+ };
86
+ }
87
+ // Milestone misses
88
+ if (milestoneStatus.consecutiveMisses >= 2) {
89
+ return {
90
+ shouldReplan: true,
91
+ scope: "tactical",
92
+ trigger: `${milestoneStatus.consecutiveMisses} consecutive milestone misses`,
93
+ urgency: "high",
94
+ reasoning: "Falling behind schedule",
95
+ };
96
+ }
97
+ // Minor issues → minor replan
98
+ if (health.recommendation === "replan_minor") {
99
+ return {
100
+ shouldReplan: true,
101
+ scope: "operational",
102
+ trigger: "Minor plan deviations",
103
+ urgency: "medium",
104
+ reasoning: health.deviations.map(d => d.description).join("; "),
105
+ };
106
+ }
107
+ return {
108
+ shouldReplan: false,
109
+ scope: "none",
110
+ trigger: "",
111
+ urgency: "low",
112
+ reasoning: "Plan healthy",
113
+ };
114
+ }
115
+ async executeReplan(plan, decision, _currentState, llmClient) {
116
+ const triggerType = decision.scope === "strategic" ? "strategic" : "error";
117
+ const severity = decision.urgency === "critical" ? "critical" :
118
+ decision.urgency === "high" ? "major" :
119
+ "minor";
120
+ const trigger = {
121
+ type: triggerType,
122
+ description: `[Proactive] ${decision.trigger}: ${decision.reasoning}`,
123
+ affectedTaskIds: [],
124
+ severity,
125
+ };
126
+ const result = await this.planner.replan(plan, trigger, llmClient);
127
+ return result.modifiedTasks;
128
+ }
129
+ }
130
+ //# sourceMappingURL=replanning-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replanning-engine.js","sourceRoot":"","sources":["../../src/planner/replanning-engine.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAiCH,2BAA2B;AAE3B,MAAM,OAAO,gBAAgB;IAEjB;IACA;IACA;IACA;IAJV,YACU,OAA4B,EAC5B,aAA4B,EAC5B,aAA4B,EAC5B,gBAAkC;QAHlC,YAAO,GAAP,OAAO,C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b,OAAO,EAAE,EAAE;YACX,OAAO,EAAE,KAAK;YACd,SAAS,EAAE,cAAc;SAC1B,CAAC;IACJ,CAAC;IAEO,KAAK,CAAC,aAAa,CACzB,IAAsB,EACtB,QAAwB,EACxB,aAAyB,EACzB,SAAqB;QAErB,MAAM,WAAW,GACf,QAAQ,CAAC,KAAK,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC;QAEzD,MAAM,QAAQ,GACZ,QAAQ,CAAC,OAAO,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;YAC9C,QAAQ,CAAC,OAAO,KAAK,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;gBACvC,OAAO,CAAC;QAEV,MAAM,OAAO,GAAkB;YAC7B,IAAI,EAAE,WAAW;YACjB,WAAW,EAAE,eAAe,QAAQ,CAAC,OAAO,KAAK,QAAQ,CAAC,SAAS,EAAE;YACrE,eAAe,EAAE,EAAE;YACnB,QAAQ;SACT,CAAC;QAEF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,SAAS,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC,aAAa,CAAC;IAC9B,CAAC;CACF"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @module planner/risk-estimator
3
+ * @description Estimates execution risk across multiple dimensions:
4
+ * build, test, scope, dependency, and token budget.
5
+ * Used by the autonomous planner to decide when to pause, re-plan, or alert.
6
+ */
7
+ import type { ImpactAnalyzer } from "../impact-analyzer.js";
8
+ import type { TransitionModel } from "../world-model/transition-model.js";
9
+ import type { WorldState } from "../world-model/state-store.js";
10
+ import type { TacticalTask } from "../hierarchical-planner.js";
11
+ export interface RiskComponents {
12
+ buildRisk: number;
13
+ testRisk: number;
14
+ scopeRisk: number;
15
+ dependencyRisk: number;
16
+ tokenRisk: number;
17
+ }
18
+ export interface RiskScore {
19
+ overall: number;
20
+ components: RiskComponents;
21
+ factors: string[];
22
+ mitigations: string[];
23
+ level: "low" | "medium" | "high" | "critical";
24
+ }
25
+ export declare class RiskEstimator {
26
+ private transitionModel;
27
+ private impactAnalyzer;
28
+ constructor(transitionModel: TransitionModel, impactAnalyzer: ImpactAnalyzer);
29
+ /**
30
+ * Estimate overall risk given current world state, remaining tasks, and resource usage.
31
+ */
32
+ estimate(currentState: WorldState, remainingTasks: TacticalTask[], completedTasks: TacticalTask[], changedFiles: string[], tokensUsed: number, tokenBudget: number): Promise<RiskScore>;
33
+ /**
34
+ * Estimate risk for a single task given the current world state.
35
+ * Returns a 0-100 score.
36
+ */
37
+ estimateTaskRisk(task: TacticalTask, state: WorldState): Promise<number>;
38
+ /**
39
+ * Returns true if the risk score's overall value meets or exceeds the threshold.
40
+ * Default threshold is 70 ("high").
41
+ */
42
+ isHighRisk(score: RiskScore, threshold?: number): boolean;
43
+ }
44
+ //# sourceMappingURL=risk-estimator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"risk-estimator.d.ts","sourceRoot":"","sources":["../../src/planner/risk-estimator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAI/D,MAAM,WAAW,cAAc;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,cAAc,CAAC;IAC3B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,WAAW,EAAE,MAAM,EAAE,CAAC;IACtB,KAAK,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAC;CAC/C;AAID,qBAAa,aAAa;IAEtB,OAAO,CAAC,eAAe;IACvB,OAAO,CAAC,cAAc;gBADd,eAAe,EAAE,eAAe,EAChC,cAAc,EAAE,cAAc;IAGxC;;OAEG;IACG,QAAQ,CACZ,YAAY,EAAE,UAAU,EACxB,cAAc,EAAE,YAAY,EAAE,EAC9B,cAAc,EAAE,YAAY,EAAE,EAC9B,YAAY,EAAE,MAAM,EAAE,EACtB,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,SAAS,CAAC;IA6ErB;;;OAGG;IACG,gBAAgB,CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC;IAmB9E;;;OAGG;IACH,UAAU,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,SAAK,GAAG,OAAO;CAGtD"}
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @module planner/risk-estimator
3
+ * @description Estimates execution risk across multiple dimensions:
4
+ * build, test, scope, dependency, and token budget.
5
+ * Used by the autonomous planner to decide when to pause, re-plan, or alert.
6
+ */
7
+ // ─── RiskEstimator ───
8
+ export class RiskEstimator {
9
+ transitionModel;
10
+ impactAnalyzer;
11
+ constructor(transitionModel, impactAnalyzer) {
12
+ this.transitionModel = transitionModel;
13
+ this.impactAnalyzer = impactAnalyzer;
14
+ }
15
+ /**
16
+ * Estimate overall risk given current world state, remaining tasks, and resource usage.
17
+ */
18
+ async estimate(currentState, remainingTasks, completedTasks, changedFiles, tokensUsed, tokenBudget) {
19
+ const factors = [];
20
+ const mitigations = [];
21
+ // 1. Build risk: if build is already failing or many files changed
22
+ let buildRisk = currentState.build.status === "fail" ? 80 : 10;
23
+ buildRisk += Math.min(changedFiles.length * 3, 40);
24
+ if (currentState.build.status === "fail") {
25
+ factors.push("Build is currently failing");
26
+ mitigations.push("Fix build errors before proceeding");
27
+ }
28
+ // 2. Test risk: if tests failing or many test files in remaining tasks
29
+ let testRisk = currentState.test.status === "fail" ? 70 : 10;
30
+ const testFilesInPlan = remainingTasks
31
+ .flatMap((t) => t.targetFiles)
32
+ .filter((f) => f.includes(".test.") || f.includes(".spec.")).length;
33
+ testRisk += Math.min(testFilesInPlan * 5, 30);
34
+ // 3. Scope risk: unexpected files being modified vs plan
35
+ const plannedFiles = new Set(completedTasks.flatMap((t) => t.targetFiles));
36
+ const unplannedChanges = changedFiles.filter((f) => !plannedFiles.has(f)).length;
37
+ const scopeRisk = Math.min(unplannedChanges * 15, 80);
38
+ if (unplannedChanges > 0) {
39
+ factors.push(`${unplannedChanges} files modified outside original plan`);
40
+ }
41
+ // 4. Dependency risk: how many remaining tasks have complex dependency chains
42
+ const avgDepsPerTask = remainingTasks.reduce((s, t) => s + t.dependsOn.length, 0) /
43
+ Math.max(remainingTasks.length, 1);
44
+ const dependencyRisk = Math.min(avgDepsPerTask * 15, 60);
45
+ // 5. Token risk: extrapolate current usage to completion
46
+ const completionRatio = completedTasks.length /
47
+ Math.max(completedTasks.length + remainingTasks.length, 1);
48
+ let tokenRisk = 0;
49
+ if (completionRatio > 0.1) {
50
+ const projectedTotal = tokensUsed / completionRatio;
51
+ const overrunRatio = projectedTotal / tokenBudget;
52
+ tokenRisk = Math.min(Math.max((overrunRatio - 0.7) * 200, 0), 100);
53
+ if (tokenRisk > 50) {
54
+ factors.push(`Projected token usage ${Math.round(overrunRatio * 100)}% of budget`);
55
+ mitigations.push("Consider reducing scope or compacting context");
56
+ }
57
+ }
58
+ const components = {
59
+ buildRisk: Math.round(Math.min(buildRisk, 100)),
60
+ testRisk: Math.round(Math.min(testRisk, 100)),
61
+ scopeRisk: Math.round(Math.min(scopeRisk, 100)),
62
+ dependencyRisk: Math.round(Math.min(dependencyRisk, 100)),
63
+ tokenRisk: Math.round(Math.min(tokenRisk, 100)),
64
+ };
65
+ // Weighted average: build and test are most important
66
+ const overall = Math.round(components.buildRisk * 0.3 +
67
+ components.testRisk * 0.25 +
68
+ components.scopeRisk * 0.2 +
69
+ components.dependencyRisk * 0.15 +
70
+ components.tokenRisk * 0.1);
71
+ const level = overall >= 85
72
+ ? "critical"
73
+ : overall >= 70
74
+ ? "high"
75
+ : overall >= 40
76
+ ? "medium"
77
+ : "low";
78
+ return { overall, components, factors, mitigations, level };
79
+ }
80
+ /**
81
+ * Estimate risk for a single task given the current world state.
82
+ * Returns a 0-100 score.
83
+ */
84
+ async estimateTaskRisk(task, state) {
85
+ let risk = 0;
86
+ // Build status contributes heavily
87
+ if (state.build.status === "fail")
88
+ risk += 40;
89
+ else if (state.build.status === "unknown")
90
+ risk += 10;
91
+ // Test status
92
+ if (state.test.status === "fail")
93
+ risk += 25;
94
+ // Number of target files (more files = more risk)
95
+ risk += Math.min(task.targetFiles.length * 5, 20);
96
+ // Number of dependencies
97
+ risk += Math.min(task.dependsOn.length * 5, 15);
98
+ return Math.min(risk, 100);
99
+ }
100
+ /**
101
+ * Returns true if the risk score's overall value meets or exceeds the threshold.
102
+ * Default threshold is 70 ("high").
103
+ */
104
+ isHighRisk(score, threshold = 70) {
105
+ return score.overall >= threshold;
106
+ }
107
+ }
108
+ //# sourceMappingURL=risk-estimator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"risk-estimator.js","sourceRoot":"","sources":["../../src/planner/risk-estimator.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAyBH,wBAAwB;AAExB,MAAM,OAAO,aAAa;IAEd;IACA;IAFV,YACU,eAAgC,EAChC,cAA8B;QAD9B,oBAAe,GAAf,eAAe,CAAiB;QAChC,mBAAc,GAAd,cAAc,CAAgB;IACrC,CAAC;IAEJ;;OAEG;IACH,KAAK,CAAC,QAAQ,CACZ,YAAwB,EACxB,cAA8B,EAC9B,cAA8B,EAC9B,YAAsB,EACtB,UAAkB,EAClB,WAAmB;Q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C,CAAC;QAEb,mCAAmC;QACnC,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,KAAK,MAAM;YAAE,IAAI,IAAI,EAAE,CAAC;aACzC,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,KAAK,SAAS;YAAE,IAAI,IAAI,EAAE,CAAC;QAEtD,cAAc;QACd,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,KAAK,MAAM;YAAE,IAAI,IAAI,EAAE,CAAC;QAE7C,kDAAkD;QAClD,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;QAElD,yBAAyB;QACzB,IAAI,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;QAEhD,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAC7B,CAAC;IAED;;;OAGG;IACH,UAAU,CAAC,KAAgB,EAAE,SAAS,GAAG,EAAE;QACzC,OAAO,KAAK,CAAC,OAAO,IAAI,SAAS,CAAC;IACpC,CAAC;CACF"}
@@ -0,0 +1,8 @@
1
+ export { StateStore } from "./state-store.js";
2
+ export type { WorldState, FileState, BuildState, TestState, GitState, DepsState, FilePatch, StatePatch, PatchHistoryEntry, MemoryStats, StateHistoryEntry, } from "./state-store.js";
3
+ export { TransitionModel } from "./transition-model.js";
4
+ export type { StateDelta, StateTransition } from "./transition-model.js";
5
+ export { SimulationEngine } from "./simulation-engine.js";
6
+ export type { SimulationStep, SimulationResult } from "./simulation-engine.js";
7
+ export { StateUpdater } from "./state-updater.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/world-model/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,YAAY,EACV,UAAU,EACV,SAAS,EACT,UAAU,EACV,SAAS,EACT,QAAQ,EACR,SAAS,EAET,SAAS,EACT,UAAU,EACV,iBAAiB,EACjB,WAAW,EAEX,iBAAiB,GAClB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,YAAY,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { StateStore } from "./state-store.js";
2
+ export { TransitionModel } from "./transition-model.js";
3
+ export { SimulationEngine } from "./simulation-engine.js";
4
+ export { StateUpdater } from "./state-updater.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/world-model/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAgB9C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @module world-model/simulation-engine
3
+ * @description Simulates the execution of a HierarchicalPlan against the current WorldState.
4
+ * Predicts failure probabilities and risk factors for each step before actual execution.
5
+ */
6
+ import type { HierarchicalPlan, TacticalTask } from "../hierarchical-planner.js";
7
+ import type { StateStore, WorldState } from "./state-store.js";
8
+ import type { TransitionModel } from "./transition-model.js";
9
+ export interface SimulationStep {
10
+ taskId: string;
11
+ taskDescription: string;
12
+ predictedState: WorldState;
13
+ /** Probability that this specific step fails (0.0 – 1.0) */
14
+ failureProbability: number;
15
+ /** Probability that ANY step up to and including this one fails */
16
+ cumulativeFailureProbability: number;
17
+ riskFactors: string[];
18
+ estimatedIterations: number;
19
+ }
20
+ export interface SimulationResult {
21
+ planId: string;
22
+ steps: SimulationStep[];
23
+ /** 1 – P(any step fails) */
24
+ overallSuccessProbability: number;
25
+ /** taskIds where failureProbability > 0.3 */
26
+ criticalSteps: string[];
27
+ /** Sum of task.estimatedIterations * 2000 */
28
+ estimatedTotalTokens: number;
29
+ warnings: string[];
30
+ simulatedAt: number;
31
+ }
32
+ export declare class SimulationEngine {
33
+ private transitionModel;
34
+ private stateStore;
35
+ constructor(transitionModel: TransitionModel, stateStore: StateStore);
36
+ /**
37
+ * Simulate the entire plan — call this after createHierarchicalPlan().
38
+ * Walks tactical tasks in order, predicting failure and state at each step.
39
+ */
40
+ simulate(plan: HierarchicalPlan): Promise<SimulationResult>;
41
+ /**
42
+ * Simulate a single tactical task given the current WorldState.
43
+ * Aggregates per-tool predictions across the task's toolStrategy.
44
+ */
45
+ simulateTask(task: TacticalTask, currentState: WorldState): SimulationStep;
46
+ /**
47
+ * Predict the WorldState at a specific task index (0-based).
48
+ * Replays simulation up to (and including) taskIndex.
49
+ */
50
+ predictStateAt(plan: HierarchicalPlan, taskIndex: number): WorldState;
51
+ /**
52
+ * Format the simulation result for injection into an LLM prompt.
53
+ */
54
+ formatForPrompt(result: SimulationResult): string;
55
+ /** Apply an aggregated delta to produce a new WorldState. Never mutates input. */
56
+ private _applyAggregateDelta;
57
+ }
58
+ //# sourceMappingURL=simulation-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simulation-engine.d.ts","sourceRoot":"","sources":["../../src/world-model/simulation-engine.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AACjF,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,k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Simulates the execution of a HierarchicalPlan against the current WorldState.
4
+ * Predicts failure probabilities and risk factors for each step before actual execution.
5
+ */
6
+ // ─── SimulationEngine ───
7
+ export class SimulationEngine {
8
+ transitionModel;
9
+ stateStore;
10
+ constructor(transitionModel, stateStore) {
11
+ this.transitionModel = transitionModel;
12
+ this.stateStore = stateStore;
13
+ }
14
+ /**
15
+ * Simulate the entire plan — call this after createHierarchicalPlan().
16
+ * Walks tactical tasks in order, predicting failure and state at each step.
17
+ */
18
+ async simulate(plan) {
19
+ let currentState = this.stateStore.getState();
20
+ const steps = [];
21
+ // Cumulative survival probability: starts at 1.0 (no failures yet)
22
+ let survivalProbability = 1.0;
23
+ for (const task of plan.tactical) {
24
+ const step = this.simulateTask(task, currentState);
25
+ // Cumulative: P(all previous steps succeed AND this one fails)
26
+ survivalProbability *= 1 - step.failureProbability;
27
+ step.cumulativeFailureProbability = 1 - survivalProbability;
28
+ steps.push(step);
29
+ // Advance state for the next step's simulation
30
+ currentState = step.predictedState;
31
+ }
32
+ const overallSuccessProbability = survivalProbability;
33
+ const criticalSteps = steps
34
+ .filter((s) => s.failureProbability > 0.3)
35
+ .map((s) => s.taskId);
36
+ const estimatedTotalTokens = plan.tactical.reduce((sum, t) => sum + t.estimatedIterations * 2000, 0);
37
+ const warnings = [];
38
+ if (overallSuccessProbability < 0.5) {
39
+ warnings.push("High risk plan: less than 50% chance of full success");
40
+ }
41
+ for (const step of steps) {
42
+ if (step.predictedState.build.status === "fail") {
43
+ warnings.push(`Build may break at step ${step.taskId}`);
44
+ }
45
+ }
46
+ return {
47
+ planId: plan.id,
48
+ steps,
49
+ overallSuccessProbability,
50
+ criticalSteps,
51
+ estimatedTotalTokens,
52
+ warnings,
53
+ simulatedAt: Date.now(),
54
+ };
55
+ }
56
+ /**
57
+ * Simulate a single tactical task given the current WorldState.
58
+ * Aggregates per-tool predictions across the task's toolStrategy.
59
+ */
60
+ simulateTask(task, currentState) {
61
+ const targetFile = task.targetFiles[0];
62
+ const argsForTool = targetFile ? { path: targetFile } : {};
63
+ // Aggregate deltas and failure probabilities from all tools in the strategy
64
+ const allFilesChanged = [];
65
+ const allFilesCreated = [];
66
+ const allFilesDeleted = [];
67
+ let buildInvalidated = false;
68
+ let testInvalidated = false;
69
+ let gitDirty = false;
70
+ // Product of (1 - p_i) — we'll convert to failure probability after the loop
71
+ let survivalProduct = 1.0;
72
+ const riskFactors = [];
73
+ for (const toolName of task.toolStrategy) {
74
+ const transition = this.transitionModel.predict(toolName, argsForTool, currentState);
75
+ const delta = transition.expectedDelta;
76
+ // Aggregate file changes
77
+ allFilesChanged.push(...delta.filesChanged);
78
+ allFilesCreated.push(...delta.filesCreated);
79
+ allFilesDeleted.push(...delta.filesDeleted);
80
+ if (delta.buildInvalidated)
81
+ buildInvalidated = true;
82
+ if (delta.testInvalidated)
83
+ testInvalidated = true;
84
+ if (delta.gitDirty)
85
+ gitDirty = true;
86
+ survivalProduct *= 1 - transition.failureProbability;
87
+ if (transition.failureProbability > 0.1) {
88
+ riskFactors.push(`${toolName}: ${transition.reasoning}`);
89
+ }
90
+ }
91
+ // If toolStrategy is empty, default to 0 failure probability (no-op task)
92
+ const failureProbability = task.toolStrategy.length > 0 ? 1 - survivalProduct : 0;
93
+ // Build predicted state by applying the aggregated delta
94
+ const predictedState = this._applyAggregateDelta(currentState, {
95
+ filesChanged: [...new Set(allFilesChanged)],
96
+ filesCreated: [...new Set(allFilesCreated)],
97
+ filesDeleted: [...new Set(allFilesDeleted)],
98
+ buildInvalidated,
99
+ testInvalidated,
100
+ gitDirty,
101
+ });
102
+ return {
103
+ taskId: task.id,
104
+ taskDescription: task.description,
105
+ predictedState,
106
+ failureProbability,
107
+ cumulativeFailureProbability: 0, // will be set by simulate()
108
+ riskFactors,
109
+ estimatedIterations: task.estimatedIterations,
110
+ };
111
+ }
112
+ /**
113
+ * Predict the WorldState at a specific task index (0-based).
114
+ * Replays simulation up to (and including) taskIndex.
115
+ */
116
+ predictStateAt(plan, taskIndex) {
117
+ let currentState = this.stateStore.getState();
118
+ for (let i = 0; i <= taskIndex && i < plan.tactical.length; i++) {
119
+ const task = plan.tactical[i];
120
+ const step = this.simulateTask(task, currentState);
121
+ currentState = step.predictedState;
122
+ }
123
+ return currentState;
124
+ }
125
+ /**
126
+ * Format the simulation result for injection into an LLM prompt.
127
+ */
128
+ formatForPrompt(result) {
129
+ const lines = [
130
+ `## Plan Simulation (${Math.round(result.overallSuccessProbability * 100)}% success probability)`,
131
+ ];
132
+ if (result.criticalSteps.length > 0) {
133
+ lines.push(`⚠️ Critical steps (high risk): ${result.criticalSteps.join(", ")}`);
134
+ }
135
+ for (const w of result.warnings) {
136
+ lines.push(`⚠️ ${w}`);
137
+ }
138
+ lines.push(`Estimated tokens: ~${result.estimatedTotalTokens.toLocaleString()}`);
139
+ return lines.join("\n");
140
+ }
141
+ // ─── Private Helpers ───
142
+ /** Apply an aggregated delta to produce a new WorldState. Never mutates input. */
143
+ _applyAggregateDelta(state, delta) {
144
+ const nextFiles = new Map(state.files);
145
+ const now = Date.now();
146
+ for (const path of delta.filesChanged) {
147
+ const existing = nextFiles.get(path);
148
+ nextFiles.set(path, {
149
+ path,
150
+ exists: true,
151
+ hash: "",
152
+ lines: existing?.lines ?? 0,
153
+ lastModified: now,
154
+ });
155
+ }
156
+ for (const path of delta.filesCreated) {
157
+ nextFiles.set(path, {
158
+ path,
159
+ exists: true,
160
+ hash: "",
161
+ lines: 0,
162
+ lastModified: now,
163
+ });
164
+ }
165
+ for (const path of delta.filesDeleted) {
166
+ const existing = nextFiles.get(path);
167
+ if (existing) {
168
+ nextFiles.set(path, { ...existing, exists: false });
169
+ }
170
+ }
171
+ const nextBuild = delta.buildInvalidated
172
+ ? { ...state.build, status: "unknown" }
173
+ : state.build;
174
+ const nextTest = delta.testInvalidated
175
+ ? { ...state.test, status: "unknown" }
176
+ : state.test;
177
+ let nextGit = state.git;
178
+ if (delta.gitDirty && !state.git.dirty) {
179
+ nextGit = { ...state.git, dirty: true };
180
+ }
181
+ return {
182
+ ...state,
183
+ files: nextFiles,
184
+ build: nextBuild,
185
+ test: nextTest,
186
+ git: nextGit,
187
+ timestamp: now,
188
+ };
189
+ }
190
+ }
191
+ //# sourceMappingURL=simulation-engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simulation-engine.js","sourceRoot":"","sources":["../../src/world-model/simulation-engine.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAiCH,2BAA2B;AAE3B,MAAM,OAAO,gBAAgB;IAEjB;IACA;IAFV,YACU,eAAgC,EAChC,UAAsB;QADtB,oBAAe,GAAf,eAAe,CAAiB;QAChC,eAAU,GAAV,UAAU,CAAY;IAC7B,CAAC;IAEJ;;;OAGG;IACH,KAAK,CAAC,QAAQ,CAAC,IAAsB;QACnC,IAAI,YAAY,GAAG,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;QAC9C,MAAM,KAAK,GAAqB,EAAE,CAAC;QAEnC,mEAAmE;QACnE,IAAI,mBAAmB,GAAG,GAAG,CAAC;QAE9B,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YACjC,MAAM,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;YAEnD,+DAA+D;YAC/D,mBAAmB,IAAI,CAAC,GAAG,IAAI,CAAC,kBAAkB,CAAC;YACnD,IAAI,CAAC,4BAA4B,GAAG,CAAC,GAAG,mBAAmB,CAAC;YAE5D,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACjB,+CAA+C;YAC/C,YAAY,GAAG,IAAI,CAAC,cAAc,CAAC;QACrC,CAAC;QAED,MAAM,yBAAyB,GAAG,mBAAmB,CAAC;QACtD,MAAM,aAAa,GAAG,KAAK;aACxB,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,kBAAkB,GAAG,GAAG,CAAC;aACzC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CA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