@h-rig/core 0.0.6-alpha.154 → 0.0.6-alpha.156

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.
@@ -1,361 +0,0 @@
1
- // @bun
2
- // packages/core/src/stageResolve.ts
3
- class PipelineUnresolvableError extends Error {
4
- cycles;
5
- contributors;
6
- constructor(message, cycles, contributors) {
7
- super(message);
8
- this.name = "PipelineUnresolvableError";
9
- this.cycles = cycles;
10
- this.contributors = contributors;
11
- }
12
- }
13
- function uniqueSorted(values) {
14
- return Array.from(new Set(values)).sort((left, right) => left.localeCompare(right));
15
- }
16
- function wrapperForMutation(mutation) {
17
- return "wrapper" in mutation ? mutation.wrapper : mutation.around;
18
- }
19
- function contributorOf(mutation) {
20
- if (mutation.contributedBy?.trim())
21
- return mutation.contributedBy;
22
- if (mutation.op === "wrap") {
23
- const wrapper = wrapperForMutation(mutation);
24
- if (wrapper.id?.trim())
25
- return wrapper.id;
26
- }
27
- return "anonymous";
28
- }
29
- function stableMutationCompare(left, right) {
30
- const leftTarget = left.op === "insert" ? left.stage.id : left.id;
31
- const rightTarget = right.op === "insert" ? right.stage.id : right.id;
32
- const targetDelta = leftTarget.localeCompare(rightTarget);
33
- if (targetDelta !== 0)
34
- return targetDelta;
35
- return contributorOf(left).localeCompare(contributorOf(right));
36
- }
37
- function ensureUniqueStageIds(stages) {
38
- const seen = new Set;
39
- for (const stage of stages) {
40
- if (seen.has(stage.id)) {
41
- throw new PipelineUnresolvableError(`Duplicate stage id: ${stage.id}`, [], []);
42
- }
43
- seen.add(stage.id);
44
- }
45
- }
46
- function assertNoDuplicateMutationTargets(mutations, op) {
47
- const seen = new Map;
48
- for (const mutation of mutations.filter((entry) => entry.op === op)) {
49
- const id = mutation.op === "insert" ? mutation.stage.id : mutation.id;
50
- const previous = seen.get(id);
51
- if (previous) {
52
- throw new PipelineUnresolvableError(`Duplicate ${op} mutation for stage ${id}: ${previous}, ${contributorOf(mutation)}`, [], uniqueSorted([previous, contributorOf(mutation)]));
53
- }
54
- seen.set(id, contributorOf(mutation));
55
- }
56
- }
57
- function mergeAnchors(current, incoming) {
58
- return uniqueSorted([...current, ...incoming ?? []]);
59
- }
60
- function stagePriority(stage) {
61
- return typeof stage.priority === "number" && Number.isFinite(stage.priority) ? stage.priority : 0;
62
- }
63
- function readyCompare(states) {
64
- return (left, right) => {
65
- const leftState = states.get(left);
66
- const rightState = states.get(right);
67
- const priorityDelta = stagePriority(rightState?.stage ?? { id: right }) - stagePriority(leftState?.stage ?? { id: left });
68
- if (priorityDelta !== 0)
69
- return priorityDelta;
70
- if (leftState?.baseIndex !== null && rightState?.baseIndex !== null && leftState?.baseIndex !== rightState?.baseIndex) {
71
- return (leftState?.baseIndex ?? 0) - (rightState?.baseIndex ?? 0);
72
- }
73
- if (leftState?.baseIndex !== null && rightState?.baseIndex === null)
74
- return -1;
75
- if (leftState?.baseIndex === null && rightState?.baseIndex !== null)
76
- return 1;
77
- return left.localeCompare(right);
78
- };
79
- }
80
- function findCycles(nodes, edges) {
81
- const adjacency = new Map;
82
- for (const node of nodes)
83
- adjacency.set(node, []);
84
- for (const edge of edges)
85
- adjacency.get(edge.from)?.push(edge.to);
86
- for (const targets of adjacency.values())
87
- targets.sort((left, right) => left.localeCompare(right));
88
- let nextIndex = 0;
89
- const indexByNode = new Map;
90
- const lowByNode = new Map;
91
- const stack = [];
92
- const onStack = new Set;
93
- const cycles = [];
94
- const visit = (node) => {
95
- indexByNode.set(node, nextIndex);
96
- lowByNode.set(node, nextIndex);
97
- nextIndex += 1;
98
- stack.push(node);
99
- onStack.add(node);
100
- for (const target of adjacency.get(node) ?? []) {
101
- if (!indexByNode.has(target)) {
102
- visit(target);
103
- lowByNode.set(node, Math.min(lowByNode.get(node) ?? 0, lowByNode.get(target) ?? 0));
104
- } else if (onStack.has(target)) {
105
- lowByNode.set(node, Math.min(lowByNode.get(node) ?? 0, indexByNode.get(target) ?? 0));
106
- }
107
- }
108
- if (lowByNode.get(node) !== indexByNode.get(node))
109
- return;
110
- const component = [];
111
- let current;
112
- do {
113
- current = stack.pop();
114
- if (current) {
115
- onStack.delete(current);
116
- component.push(current);
117
- }
118
- } while (current && current !== node);
119
- const hasSelfLoop = edges.some((edge) => edge.from === node && edge.to === node);
120
- if (component.length > 1 || hasSelfLoop) {
121
- cycles.push(component.sort((left, right) => left.localeCompare(right)));
122
- }
123
- };
124
- for (const node of [...nodes].sort((left, right) => left.localeCompare(right))) {
125
- if (!indexByNode.has(node))
126
- visit(node);
127
- }
128
- return cycles.sort((left, right) => left.join("\x00").localeCompare(right.join("\x00")));
129
- }
130
- function topologicalOrder(states, edges) {
131
- const nodes = [...states.keys()];
132
- const outgoing = new Map;
133
- const indegree = new Map;
134
- for (const node of nodes) {
135
- outgoing.set(node, []);
136
- indegree.set(node, 0);
137
- }
138
- for (const edge of edges) {
139
- outgoing.get(edge.from)?.push(edge.to);
140
- indegree.set(edge.to, (indegree.get(edge.to) ?? 0) + 1);
141
- }
142
- for (const targets of outgoing.values())
143
- targets.sort((left, right) => left.localeCompare(right));
144
- const compare = readyCompare(states);
145
- const ready = nodes.filter((node) => (indegree.get(node) ?? 0) === 0).sort(compare);
146
- const order = [];
147
- while (ready.length > 0) {
148
- const node = ready.shift();
149
- if (!node)
150
- break;
151
- order.push(node);
152
- for (const target of outgoing.get(node) ?? []) {
153
- const next = (indegree.get(target) ?? 0) - 1;
154
- indegree.set(target, next);
155
- if (next === 0) {
156
- ready.push(target);
157
- ready.sort(compare);
158
- }
159
- }
160
- }
161
- if (order.length === nodes.length)
162
- return order;
163
- const cycles = findCycles(nodes, edges);
164
- const cycleMembers = new Set(cycles.flat());
165
- const contributors = uniqueSorted(edges.filter((edge) => cycleMembers.has(edge.from) && cycleMembers.has(edge.to)).flatMap((edge) => edge.contributors));
166
- throw new PipelineUnresolvableError(`Stage pipeline has unresolved cycle: ${cycles.map((cycle) => cycle.join(" -> ")).join("; ")}`, cycles, contributors);
167
- }
168
- function composeStageWrappers(state) {
169
- const wrappers = state.wrappers.toSorted((left, right) => {
170
- const priorityDelta = (right.wrapper.priority ?? 0) - (left.wrapper.priority ?? 0);
171
- if (priorityDelta !== 0)
172
- return priorityDelta;
173
- return left.contributedBy.localeCompare(right.contributedBy);
174
- });
175
- let stage = state.stage;
176
- for (const wrapper of wrappers.toReversed()) {
177
- if (wrapper.wrapper.apply)
178
- stage = wrapper.wrapper.apply(stage);
179
- }
180
- return stage;
181
- }
182
- function resolveStagePipeline(input) {
183
- ensureUniqueStageIds(input.defaultStages);
184
- const mutations = [...input.mutations ?? []];
185
- assertNoDuplicateMutationTargets(mutations, "insert");
186
- assertNoDuplicateMutationTargets(mutations, "replace");
187
- const states = new Map;
188
- const removedStates = new Map;
189
- for (const [index, stage] of input.defaultStages.entries()) {
190
- states.set(stage.id, {
191
- stage: { ...stage, protected: false },
192
- before: [...stage.before ?? []],
193
- after: [...stage.after ?? []],
194
- baseIndex: index,
195
- contributedBy: "default",
196
- wrappers: [],
197
- droppedAnchors: [],
198
- isProtected: false
199
- });
200
- }
201
- for (const mutation of mutations.filter((entry) => entry.op === "remove").sort(stableMutationCompare)) {
202
- const state = states.get(mutation.id);
203
- const contributor = contributorOf(mutation);
204
- if (!state)
205
- continue;
206
- const removedState = {
207
- ...state,
208
- removedBy: contributor
209
- };
210
- removedStates.set(mutation.id, removedState);
211
- states.delete(mutation.id);
212
- }
213
- for (const mutation of mutations.filter((entry) => entry.op === "replace").sort(stableMutationCompare)) {
214
- const state = states.get(mutation.id);
215
- const contributor = contributorOf(mutation);
216
- if (!state)
217
- continue;
218
- const replacement = { ...mutation.stage, id: mutation.id, protected: false };
219
- states.set(mutation.id, {
220
- ...state,
221
- stage: replacement,
222
- before: mutation.stage.before ? [...mutation.stage.before] : state.before,
223
- after: mutation.stage.after ? [...mutation.stage.after] : state.after,
224
- replacedBy: contributor,
225
- contributedBy: state.contributedBy,
226
- isProtected: false
227
- });
228
- }
229
- for (const mutation of mutations.filter((entry) => entry.op === "insert").sort(stableMutationCompare)) {
230
- const contributor = contributorOf(mutation);
231
- if (states.has(mutation.stage.id)) {
232
- throw new PipelineUnresolvableError(`Inserted stage ${mutation.stage.id} conflicts with an existing stage`, [], [contributor]);
233
- }
234
- states.set(mutation.stage.id, {
235
- stage: { ...mutation.stage, protected: false },
236
- before: [...mutation.stage.before ?? []],
237
- after: [...mutation.stage.after ?? []],
238
- baseIndex: null,
239
- contributedBy: contributor,
240
- wrappers: [],
241
- droppedAnchors: [],
242
- isProtected: false
243
- });
244
- }
245
- for (const mutation of mutations.filter((entry) => entry.op === "reorder").sort(stableMutationCompare)) {
246
- const state = states.get(mutation.id);
247
- if (!state)
248
- continue;
249
- states.set(mutation.id, {
250
- ...state,
251
- before: mergeAnchors(state.before, mutation.before),
252
- after: mergeAnchors(state.after, mutation.after)
253
- });
254
- }
255
- for (const mutation of mutations.filter((entry) => entry.op === "wrap").sort(stableMutationCompare)) {
256
- const state = states.get(mutation.id);
257
- const contributor = contributorOf(mutation);
258
- const wrapper = wrapperForMutation(mutation);
259
- if (!state)
260
- continue;
261
- states.set(mutation.id, {
262
- ...state,
263
- wrappers: [...state.wrappers, { contributedBy: contributor, wrapper }]
264
- });
265
- }
266
- const contributorsForAnchor = (stageId, direction, anchor, state) => {
267
- const contributors = new Set;
268
- if (state.replacedBy)
269
- contributors.add(state.replacedBy);
270
- for (const mutation of mutations) {
271
- if (mutation.op === "reorder" && mutation.id === stageId && (direction === "before" ? mutation.before : mutation.after)?.includes(anchor)) {
272
- contributors.add(contributorOf(mutation));
273
- }
274
- if (mutation.op === "insert" && mutation.stage.id === stageId && (direction === "before" ? mutation.stage.before : mutation.stage.after)?.includes(anchor)) {
275
- contributors.add(contributorOf(mutation));
276
- }
277
- }
278
- if (contributors.size === 0)
279
- contributors.add(state.contributedBy);
280
- return uniqueSorted(contributors);
281
- };
282
- const edges = [];
283
- for (const [stageId, state] of states) {
284
- const before = [];
285
- const after = [];
286
- for (const anchor of state.before) {
287
- if (states.has(anchor))
288
- before.push(anchor);
289
- else {
290
- const removed = removedStates.get(anchor);
291
- state.droppedAnchors.push({
292
- stageId,
293
- anchor,
294
- direction: "before",
295
- reason: removed ? "removed" : "missing",
296
- ...removed?.removedBy ? { removedBy: removed.removedBy } : {}
297
- });
298
- }
299
- }
300
- for (const anchor of state.after) {
301
- if (states.has(anchor))
302
- after.push(anchor);
303
- else {
304
- const removed = removedStates.get(anchor);
305
- state.droppedAnchors.push({
306
- stageId,
307
- anchor,
308
- direction: "after",
309
- reason: removed ? "removed" : "missing",
310
- ...removed?.removedBy ? { removedBy: removed.removedBy } : {}
311
- });
312
- }
313
- }
314
- state.before = uniqueSorted(before);
315
- state.after = uniqueSorted(after);
316
- for (const target of state.before)
317
- edges.push({ from: stageId, to: target, contributors: contributorsForAnchor(stageId, "before", target, state) });
318
- for (const source of state.after)
319
- edges.push({ from: source, to: stageId, contributors: contributorsForAnchor(stageId, "after", source, state) });
320
- }
321
- const order = topologicalOrder(states, edges);
322
- const stages = [];
323
- const record = [];
324
- for (const id of order) {
325
- const state = states.get(id);
326
- if (!state)
327
- continue;
328
- stages.push(composeStageWrappers(state));
329
- const wrappedBy = state.wrappers.toSorted((left, right) => {
330
- const priorityDelta = (right.wrapper.priority ?? 0) - (left.wrapper.priority ?? 0);
331
- if (priorityDelta !== 0)
332
- return priorityDelta;
333
- return left.contributedBy.localeCompare(right.contributedBy);
334
- }).map((wrapper) => wrapper.contributedBy);
335
- record.push({
336
- stageId: id,
337
- contributedBy: state.contributedBy,
338
- ...state.replacedBy ? { replacedBy: state.replacedBy } : {},
339
- ...wrappedBy.length > 0 ? { wrappedBy } : {},
340
- ...state.droppedAnchors.length > 0 ? { droppedAnchors: state.droppedAnchors.toSorted((left, right) => left.anchor.localeCompare(right.anchor)) } : {},
341
- isProtected: state.isProtected
342
- });
343
- }
344
- record.push(...[...removedStates.entries()].toSorted((left, right) => {
345
- const leftIndex = left[1].baseIndex ?? Number.MAX_SAFE_INTEGER;
346
- const rightIndex = right[1].baseIndex ?? Number.MAX_SAFE_INTEGER;
347
- if (leftIndex !== rightIndex)
348
- return leftIndex - rightIndex;
349
- return left[0].localeCompare(right[0]);
350
- }).map(([stageId, state]) => ({
351
- stageId,
352
- contributedBy: state.contributedBy,
353
- ...state.removedBy ? { removedBy: state.removedBy } : {},
354
- isProtected: state.isProtected
355
- })));
356
- return { stages, order, record, cycles: [] };
357
- }
358
- export {
359
- resolveStagePipeline,
360
- PipelineUnresolvableError
361
- };
@@ -1,64 +0,0 @@
1
- import type { TaskSummary } from "@rig/contracts";
2
- export type TaskDependencyProjection = Pick<TaskSummary, "id" | "status" | "priority" | "metadata"> & Partial<Pick<TaskSummary, "externalId" | "sourceIssueId" | "dependencies" | "parentChildDeps" | "createdAt" | "updatedAt" | "role" | "scope" | "validationKeys">> & {
3
- readonly title?: string | null;
4
- };
5
- export type TaskDependencyBadgeKind = "blocked" | "ready" | "dependency";
6
- export interface TaskDependencyBadge {
7
- readonly kind: TaskDependencyBadgeKind;
8
- readonly label: string;
9
- readonly description: string;
10
- readonly count?: number;
11
- readonly taskIds?: readonly string[];
12
- }
13
- export interface TaskDependencyBadgeSummary {
14
- readonly taskId: string;
15
- readonly blockingDepth: number;
16
- readonly dependencyIds: readonly string[];
17
- readonly unresolvedDependencyRefs: readonly string[];
18
- readonly blockedBy: readonly string[];
19
- readonly blocks: readonly string[];
20
- readonly blocked: boolean;
21
- readonly ready: boolean;
22
- readonly dependencyCount: number;
23
- readonly dependentCount: number;
24
- readonly badges: readonly TaskDependencyBadge[];
25
- }
26
- export declare function readTaskMetadataStringList(task: TaskDependencyProjection, key: "dependencies" | "parentChildDeps" | "labels"): string[];
27
- export declare function readTaskBlockingDependencyRefs(task: TaskDependencyProjection): string[];
28
- export declare function readTaskDependencyRefs(task: TaskDependencyProjection): string[];
29
- export declare function readTaskSourceIssueId(task: TaskDependencyProjection): string | null;
30
- export declare function readTaskScope(task: TaskDependencyProjection): string[];
31
- export type TaskScopeInput = readonly string[] | TaskDependencyProjection;
32
- export declare function disjointScope(left: TaskScopeInput, right: TaskScopeInput): boolean;
33
- export declare function resolveTaskReference(ref: string, tasksById: ReadonlyMap<string, TaskDependencyProjection>, taskIdByExternalRef: ReadonlyMap<string, string>, taskIdBySourceIssueId: ReadonlyMap<string, string>): string | null;
34
- export declare function buildTaskReferenceIndex<T extends TaskDependencyProjection>(tasks: readonly T[]): {
35
- readonly tasksById: Map<string, T>;
36
- readonly taskIdByExternalRef: Map<string, string>;
37
- readonly taskIdBySourceIssueId: Map<string, string>;
38
- };
39
- export declare function computeTaskBlockingDepths<T extends TaskDependencyProjection>(tasks: readonly T[]): Map<string, number>;
40
- export declare function isTaskTerminalStatus(status: string | null | undefined): boolean;
41
- export declare function computeTaskDependencyBadges(tasks: readonly TaskDependencyProjection[]): Map<string, TaskDependencyBadgeSummary>;
42
- export declare function selectNextReadyTaskByPriority<T extends TaskDependencyProjection>(tasks: readonly T[], options?: {
43
- readonly excludeTaskIds?: Iterable<string>;
44
- readonly filter?: (task: T) => boolean;
45
- }): T | null;
46
- export type ReadyTaskSelectionMode = "all-ready" | "blocking-only" | "max-unblock";
47
- export interface RankedReadyTask<T extends TaskDependencyProjection> {
48
- readonly task: T;
49
- readonly score: number;
50
- readonly priority: number;
51
- readonly unblockCount: number;
52
- readonly scope: readonly string[];
53
- }
54
- export interface RankedReadyTaskOptions<T extends TaskDependencyProjection> {
55
- readonly excludeTaskIds?: Iterable<string>;
56
- readonly activeTaskIds?: Iterable<string>;
57
- readonly filter?: (task: T) => boolean;
58
- readonly selection?: ReadyTaskSelectionMode;
59
- readonly requireDisjointScopes?: boolean;
60
- readonly disjointWithScopes?: Iterable<string>;
61
- readonly limit?: number;
62
- }
63
- export declare function rankReadyTasks<T extends TaskDependencyProjection>(tasks: readonly T[], options?: Omit<RankedReadyTaskOptions<T>, "limit" | "requireDisjointScopes" | "disjointWithScopes">): readonly RankedReadyTask<T>[];
64
- export declare function selectRankedReadyTasks<T extends TaskDependencyProjection>(tasks: readonly T[], options?: RankedReadyTaskOptions<T>): readonly T[];