@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 304 lines 9.3 KB
Raw
1 import { toPath } from "../FQN.ts";
2 import type { BindingAction, CRUD, ActionApply, ActionDelete, Plan } from "../Plan.ts";
3 import type { ProviderMode } from "../ProviderMode.ts";
4 import {
5 formatDeclaredPropertyYaml,
6 formatDriftPropertyYaml,
7 type DeclaredPropertyYaml,
8 } from "./PropertyDiff.ts";
9
10 export type ActionTreeItem = ActionApply | ActionDelete;
11 export type ActionVerb = ActionTreeItem["action"]; // "run" | "noop" | "delete"
12
13 /** No-op actions are dependency markers, not work the user needs to review. */
14 export const actionHasPlannedWork = (item: ActionTreeItem): boolean => item.action !== "noop";
15
16 export interface PlanSummaryCounts {
17 readonly counts: Record<
18 "create" | "update" | "adopted" | "delete" | "orphaned" | "replace" | "noop",
19 number
20 >;
21 readonly taskCounts: Record<"run" | "delete" | "noop", number>;
22 readonly bindingChanges: number;
23 }
24
25 /** Count every resource and task, plus binding changes, for the Plan summary. */
26 export const buildPlanSummary = (plan: Plan): PlanSummaryCounts => {
27 const allItems = [...Object.values(plan.resources), ...Object.values(plan.deletions)].filter(
28 (item): item is CRUD => item !== undefined,
29 );
30 const counts = {
31 create: 0,
32 update: 0,
33 adopted: 0,
34 delete: 0,
35 orphaned: 0,
36 noop: 0,
37 replace: 0,
38 };
39 for (const item of allItems) {
40 counts[item.action]++;
41 }
42 const taskCounts = { run: 0, noop: 0, delete: 0 };
43 for (const item of [
44 ...Object.values(plan.actions ?? {}),
45 ...Object.values(plan.actionDeletions ?? {}),
46 ].filter((task): task is ActionTreeItem => task !== undefined)) {
47 taskCounts[item.action]++;
48 }
49 const bindingChanges = allItems.reduce(
50 (count, item) => count + item.bindings.filter((binding) => binding.action !== "noop").length,
51 0,
52 );
53 return { counts, taskCounts, bindingChanges };
54 };
55
56 /**
57 * A tree node representing a namespace.
58 * Resources and tasks live directly inside the namespace where they were
59 * created.
60 */
61 export interface TreeNode {
62 id: string;
63 path: string[];
64 children: Map<string, TreeNode>;
65 resources: CRUD[];
66 actions: ActionTreeItem[];
67 }
68
69 export type DerivedAction =
70 | "create"
71 | "update"
72 | "adopted"
73 | "delete"
74 | "orphaned"
75 | "replace"
76 | "noop"
77 | "mixed";
78
79 export function buildNamespaceTree(
80 items: CRUD[],
81 actions: ReadonlyArray<ActionTreeItem> = [],
82 ): TreeNode {
83 const root: TreeNode = {
84 id: "",
85 path: [],
86 children: new Map(),
87 resources: [],
88 actions: [],
89 };
90
91 const getNode = (path: string[]) => {
92 let current = root;
93 for (let i = 0; i < path.length; i++) {
94 const segment = path[i];
95 let child = current.children.get(segment);
96 if (!child) {
97 child = {
98 id: segment,
99 path: path.slice(0, i + 1),
100 children: new Map(),
101 resources: [],
102 actions: [],
103 };
104 current.children.set(segment, child);
105 }
106 current = child;
107 }
108 return current;
109 };
110
111 for (const item of items) {
112 getNode(toPath(item.resource.Namespace)).resources.push(item);
113 }
114 for (const action of actions) {
115 getNode(toPath(action.def.Namespace)).actions.push(action);
116 }
117
118 return root;
119 }
120
121 function deriveNamespaceAction(node: TreeNode): DerivedAction {
122 const actions = new Set<BindingAction | CRUD["action"] | DerivedAction>();
123
124 for (const resource of node.resources) {
125 actions.add(deriveResourceChildrenAction(resource, node));
126 }
127 for (const action of node.actions) {
128 // Map task actions onto the resource action space for the rollup:
129 // run → create, delete → delete, noop → noop.
130 actions.add(
131 action.action === "run" ? "create" : action.action === "delete" ? "delete" : "noop",
132 );
133 }
134 for (const child of node.children.values()) {
135 const childAction = deriveNamespaceAction(child);
136 if (childAction === "mixed") {
137 return "mixed";
138 }
139 actions.add(childAction);
140 }
141
142 return deriveAction(actions);
143 }
144
145 export interface FlattenedItem {
146 type: "namespace" | "resource" | "binding" | "action";
147 depth: number;
148 id: string;
149 path: string[];
150 action: CRUD["action"] | BindingAction | DerivedAction | ActionVerb;
151 resourceType?: string;
152 bindingSid?: string;
153 bindingCount?: number;
154 hasChildren?: boolean;
155 /** For task items, the Task's Type (e.g. "Sync"). */
156 actionType?: string;
157 /**
158 * For resource items, the {@link ProviderMode} the node's provider was
159 * resolved for. `undefined` for mode-agnostic providers.
160 */
161 providerMode?: ProviderMode;
162 /**
163 * For resource items planned as a mode-switch replacement, the mode the
164 * old generation was created with (always differs from `providerMode`).
165 */
166 fromProviderMode?: ProviderMode;
167 /** Safe YAML detail attached only when the caller opts into detailed view. */
168 propertyYaml?: DeclaredPropertyYaml;
169 }
170
171 export interface FlattenTreeOptions {
172 includePropertyYaml?: boolean;
173 }
174
175 export function flattenTree(node: TreeNode, options: FlattenTreeOptions = {}): FlattenedItem[] {
176 const result: FlattenedItem[] = [];
177 flattenNamespace(node, 0, result, options);
178 return result;
179 }
180
181 const flattenNamespace = (
182 node: TreeNode,
183 depth: number,
184 result: FlattenedItem[],
185 options: FlattenTreeOptions,
186 ) => {
187 const sortedResources = [...node.resources].sort((a, b) =>
188 a.resource.LogicalId.localeCompare(b.resource.LogicalId),
189 );
190 const sortedChildren = Array.from(node.children.entries()).sort(([a], [b]) => a.localeCompare(b));
191 const resourceIds = new Set(sortedResources.map((resource) => resource.resource.LogicalId));
192
193 for (const [id, child] of sortedChildren) {
194 if (resourceIds.has(id) || isEmpty(child)) {
195 continue;
196 }
197 result.push({
198 type: "namespace",
199 depth,
200 id,
201 path: child.path,
202 action: deriveNamespaceAction(child),
203 hasChildren: true,
204 });
205 flattenNamespace(child, depth + 1, result, options);
206 }
207
208 for (const resource of sortedResources) {
209 const childNamespace = node.children.get(resource.resource.LogicalId);
210 result.push({
211 type: "resource",
212 depth,
213 id: resource.resource.LogicalId,
214 path: [...node.path, resource.resource.LogicalId],
215 action: resource.action,
216 resourceType: resource.resource.Type,
217 bindingCount: resource.bindings.length,
218 providerMode: resource.mode,
219 fromProviderMode:
220 resource.action === "replace" &&
221 resource.mode !== undefined &&
222 resource.state.providerMode !== undefined &&
223 resource.state.providerMode !== resource.mode
224 ? resource.state.providerMode
225 : undefined,
226 propertyYaml:
227 "drift" in resource && resource.drift !== undefined
228 ? formatDriftPropertyYaml(
229 resource.drift.expected,
230 resource.drift.actual,
231 resource.drift.missing,
232 )
233 : options.includePropertyYaml &&
234 (resource.action === "create" ||
235 resource.action === "update" ||
236 resource.action === "adopted" ||
237 resource.action === "replace")
238 ? formatDeclaredPropertyYaml(
239 resource.action === "create" ? {} : resource.state.props,
240 resource.props,
241 resource.action === "adopted" ? "update" : resource.action,
242 )
243 : undefined,
244 });
245 for (const binding of [...resource.bindings].sort((a, b) => a.sid.localeCompare(b.sid))) {
246 result.push({
247 type: "binding",
248 depth: depth + 1,
249 id: binding.sid,
250 path: [...node.path, resource.resource.LogicalId, binding.sid],
251 action: binding.action,
252 bindingSid: binding.sid,
253 });
254 }
255 if (childNamespace) {
256 flattenNamespace(childNamespace, depth + 1, result, options);
257 }
258 }
259
260 // Actions are listed after resources at the same depth.
261 const sortedActions = [...node.actions].sort((a, b) =>
262 a.def.LogicalId.localeCompare(b.def.LogicalId),
263 );
264 for (const action of sortedActions) {
265 result.push({
266 type: "action",
267 depth,
268 id: action.def.LogicalId,
269 path: [...node.path, action.def.LogicalId],
270 action: action.action,
271 actionType: action.def.Type,
272 });
273 }
274 };
275
276 const isEmpty = (node: TreeNode) =>
277 node.resources.length === 0 &&
278 node.actions.length === 0 &&
279 Array.from(node.children.values()).every(isEmpty);
280
281 const deriveResourceChildrenAction = (resource: CRUD, node: TreeNode): DerivedAction => {
282 const actions = new Set<BindingAction | CRUD["action"] | DerivedAction>([resource.action]);
283 for (const binding of resource.bindings) {
284 actions.add(binding.action);
285 }
286 const childNamespace = node.children.get(resource.resource.LogicalId);
287 if (childNamespace) {
288 actions.add(deriveNamespaceAction(childNamespace));
289 }
290 return deriveAction(actions);
291 };
292
293 const deriveAction = (
294 actions: Set<BindingAction | CRUD["action"] | DerivedAction>,
295 ): DerivedAction => {
296 if (actions.size === 0) return "noop";
297 if (actions.has("replace")) return actions.size === 1 ? "replace" : "mixed";
298 if (actions.has("orphaned")) return actions.size === 1 ? "orphaned" : "mixed";
299 if (actions.has("delete")) return actions.size === 1 ? "delete" : "mixed";
300 if (actions.has("create")) return actions.size === 1 ? "create" : "mixed";
301 if (actions.has("adopted")) return actions.size === 1 ? "adopted" : "mixed";
302 if (actions.has("update")) return actions.size === 1 ? "update" : "mixed";
303 return "noop";
304 };