@oisin-ee/pi-dogsled 0.34.2 → 0.35.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.
@@ -0,0 +1,109 @@
1
+ import { History } from "./history.ts";
2
+
3
+ interface OrderChange {
4
+ readonly after: string | null;
5
+ readonly id: string;
6
+ readonly parent: string | null;
7
+ }
8
+ interface Neighbours {
9
+ readonly next: string | null;
10
+ readonly previous: string | null;
11
+ }
12
+ interface Position {
13
+ next: string | null;
14
+ readonly parent: string | null;
15
+ previous: string | null;
16
+ }
17
+ /** Links ordered tasks without copying siblings when one task moves. */
18
+ class OrderIndex {
19
+ readonly #positions = new Map<string, Position>();
20
+ readonly #heads = new History<string | null, string | null>();
21
+ readonly #next = new History<string, string | null>();
22
+ /**
23
+ * Validates and applies one link while retaining historical versions.
24
+ * @param {OrderChange | string} change Placement or removed ID.
25
+ * @param {number} revision Replay revision.
26
+ * @returns {boolean} Whether the placement changed.
27
+ */
28
+ public apply(change: OrderChange | string, revision: number): boolean {
29
+ const id = typeof change === "string" ? change : change.id,
30
+ previous = this.#positions.get(id),
31
+ changed =
32
+ typeof change === "string"
33
+ ? previous !== undefined
34
+ : previous?.parent !== change.parent || previous.previous !== change.after;
35
+ if (typeof change === "string") {
36
+ this.#remove(change, revision);
37
+ } else {
38
+ this.#place(change, revision);
39
+ }
40
+ return changed;
41
+ }
42
+
43
+ #connect(parent: string | null, pair: Readonly<Neighbours>, revision: number): void {
44
+ const previous = pair.previous === null ? undefined : this.#positions.get(pair.previous),
45
+ next = pair.next === null ? undefined : this.#positions.get(pair.next);
46
+ if (pair.previous === null) {
47
+ this.#heads.set(parent, revision, pair.next);
48
+ } else {
49
+ this.#next.set(pair.previous, revision, pair.next);
50
+ }
51
+ if (previous !== undefined) {
52
+ previous.next = pair.next;
53
+ }
54
+ if (next !== undefined) {
55
+ next.previous = pair.previous;
56
+ }
57
+ }
58
+
59
+ #remove(id: string, revision: number): void {
60
+ const position = this.#positions.get(id);
61
+ if (position !== undefined) {
62
+ this.#connect(position.parent, position, revision);
63
+ this.#positions.delete(id);
64
+ }
65
+ }
66
+
67
+ #place(change: OrderChange, revision: number): void {
68
+ const previous = change.after === null ? undefined : this.#positions.get(change.after);
69
+ if (
70
+ change.id === change.after ||
71
+ change.id === change.parent ||
72
+ (change.after !== null && previous?.parent !== change.parent)
73
+ ) {
74
+ throw new Error("INVALID_TODO_DELTA: invalid order predecessor");
75
+ }
76
+ this.#remove(change.id, revision);
77
+ const next =
78
+ change.after === null
79
+ ? (this.#heads.get(change.parent, revision) ?? null)
80
+ : (previous?.next ?? null);
81
+ this.#positions.set(change.id, { next, parent: change.parent, previous: change.after });
82
+ this.#connect(change.parent, { next: change.id, previous: change.after }, revision);
83
+ this.#connect(change.parent, { next, previous: change.id }, revision);
84
+ }
85
+
86
+ /**
87
+ * Reads ordered IDs for a historical frame.
88
+ * @param {string | null} parent Parent ID, or null for roots.
89
+ * @param {number} revision Replay revision.
90
+ * @returns {string[]} Ordered task IDs.
91
+ */
92
+ public ids(parent: string | null, revision: number): string[] {
93
+ const ids: string[] = [],
94
+ seen = new Set<string>();
95
+ let current = this.#heads.get(parent, revision) ?? null;
96
+ while (current !== null) {
97
+ if (seen.has(current)) {
98
+ throw new Error("INVALID_TODO_DELTA: cyclic order");
99
+ }
100
+ seen.add(current);
101
+ ids.push(current);
102
+ current = this.#next.get(current, revision) ?? null;
103
+ }
104
+ return ids;
105
+ }
106
+ }
107
+
108
+ export { OrderIndex };
109
+ export type { OrderChange };
@@ -0,0 +1,54 @@
1
+ import type { ExecutionRef, TodoList, UnitRef } from "./wasm.ts";
2
+
3
+ const originFor = (
4
+ reference: Readonly<UnitRef>,
5
+ entryId: string,
6
+ origins: Readonly<Map<string, string>>,
7
+ ): string => {
8
+ const key = JSON.stringify([reference.sessionId, reference.unitId, reference.revision]),
9
+ origin = origins.get(key) ?? entryId;
10
+ origins.set(key, origin);
11
+ return origin;
12
+ };
13
+
14
+ /** Derives entry provenance without rewriting the imported lead reference. */
15
+ class Provenance {
16
+ readonly #origins = new Map<string, string>();
17
+ readonly #seals = new Map<string, string>();
18
+
19
+ public list(list: TodoList): TodoList {
20
+ const current = structuredClone(list);
21
+ for (const task of current.tasks.flatMap((root) => [root, ...(root.subtasks ?? [])])) {
22
+ if (task.unit !== undefined) {
23
+ this.resolve(task.unit, "");
24
+ }
25
+ }
26
+ return current;
27
+ }
28
+
29
+ public resolve(
30
+ unit: {
31
+ readonly reference: Readonly<UnitRef>;
32
+ readonly imported?:
33
+ | {
34
+ readonly seed: { readonly execution: Readonly<ExecutionRef> };
35
+ readonly seal?: { readonly entryId: string } | undefined;
36
+ }
37
+ | undefined;
38
+ },
39
+ entryId: string,
40
+ ): void {
41
+ if (unit.imported === undefined) {
42
+ Object.assign(unit.reference, {
43
+ contractEntryId: originFor(unit.reference, entryId, this.#origins),
44
+ });
45
+ } else if (unit.imported.seal !== undefined) {
46
+ const key = JSON.stringify(unit.imported.seed.execution),
47
+ sealEntry = this.#seals.get(key) ?? entryId;
48
+ this.#seals.set(key, sealEntry);
49
+ Object.assign(unit.imported.seal, { entryId: sealEntry });
50
+ }
51
+ }
52
+ }
53
+
54
+ export { Provenance };
@@ -8,9 +8,10 @@ import type {
8
8
  UnitRef,
9
9
  } from "./wasm.ts";
10
10
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
11
- import { STATE_ENTRY, branchSnapshot } from "./state.ts";
12
11
  import type { TodoParams, TodoResult, TodoSession } from "./tool.ts";
13
12
  import { active, claim, importUnit, imported, inspect, parse, protect, settle } from "./wasm.ts";
13
+ import { branchSnapshot, entryTasks, saveState } from "./state.ts";
14
+ import type { TodoDelta } from "./state.ts";
14
15
  import { ownsTodo } from "./lifecycle.ts";
15
16
  import { repositoryIdentity } from "./repository.ts";
16
17
  import { runTodo } from "./tool.ts";
@@ -145,14 +146,10 @@ class TaskProvider {
145
146
  this.context(ctx);
146
147
  this.#mutation(() => {
147
148
  const session = this.#session(),
148
- change = importUnit(
149
- branchSnapshot(session.branch()),
150
- source,
151
- session.sessionId,
152
- repositoryIdentity(origin),
153
- );
149
+ before = branchSnapshot(session.branch()),
150
+ change = importUnit(before, source, session.sessionId, repositoryIdentity(origin));
154
151
  if (change.persist) {
155
- session.append(STATE_ENTRY, change.list);
152
+ saveState(before, change.list, session);
156
153
  }
157
154
  });
158
155
  }
@@ -175,13 +172,10 @@ class TaskProvider {
175
172
  respond(() =>
176
173
  this.#mutation(() => {
177
174
  const session = this.#session(),
178
- change = claim(
179
- branchSnapshot(session.branch()),
180
- JSON.stringify(input),
181
- session.sessionId,
182
- );
175
+ before = branchSnapshot(session.branch()),
176
+ change = claim(before, JSON.stringify(input), session.sessionId);
183
177
  if (change.persist) {
184
- session.append(STATE_ENTRY, change.list);
178
+ saveState(before, change.list, session);
185
179
  }
186
180
  return change.value;
187
181
  }),
@@ -192,13 +186,10 @@ class TaskProvider {
192
186
  respond(() =>
193
187
  this.#mutation(() => {
194
188
  const session = this.#session(),
195
- change = settle(
196
- branchSnapshot(session.branch()),
197
- JSON.stringify(input),
198
- session.sessionId,
199
- );
189
+ before = branchSnapshot(session.branch()),
190
+ change = settle(before, JSON.stringify(input), session.sessionId);
200
191
  if (change.persist) {
201
- session.append(STATE_ENTRY, change.list);
192
+ saveState(before, change.list, session);
202
193
  }
203
194
  return change.value;
204
195
  }),
@@ -243,17 +234,26 @@ class TaskProvider {
243
234
  static #importScope(ctx: ExtensionContext, branch: TodoList): void {
244
235
  const sessionId = ctx.sessionManager.getSessionId(),
245
236
  receipt = imported(branch, sessionId);
237
+ // Only changed records carry new receipts. Do not materialize lists here:
238
+ // Unrelated branches also appear in getEntries; never combine their orders.
246
239
  for (const entry of ctx.sessionManager.getEntries()) {
247
- if (entry.type === "custom" && entry.customType === STATE_ENTRY) {
248
- const recorded = imported(parse(entry.data), sessionId);
249
- if (
250
- recorded !== undefined &&
251
- (receipt === undefined ||
252
- JSON.stringify(recorded.execution) !== JSON.stringify(receipt.execution) ||
253
- recorded.digest !== receipt.digest ||
254
- (recorded.seal !== undefined && receipt.seal === undefined))
255
- ) {
256
- throw new Error("SEEDED_SCOPE_LOCKED: branch cannot discard imported scope or its seal");
240
+ for (const task of entryTasks(entry)) {
241
+ if (task.unit?.imported !== undefined) {
242
+ const recorded = imported(
243
+ parse({ tasks: [Object.assign({}, task, { subtasks: [] })] }),
244
+ sessionId,
245
+ );
246
+ if (
247
+ recorded !== undefined &&
248
+ (receipt === undefined ||
249
+ JSON.stringify(recorded.execution) !== JSON.stringify(receipt.execution) ||
250
+ recorded.digest !== receipt.digest ||
251
+ (recorded.seal !== undefined && receipt.seal === undefined))
252
+ ) {
253
+ throw new Error(
254
+ "SEEDED_SCOPE_LOCKED: branch cannot discard imported scope or its seal",
255
+ );
256
+ }
257
257
  }
258
258
  }
259
259
  }
@@ -265,11 +265,11 @@ class TaskProvider {
265
265
  throw new Error("PROVIDER_UNAVAILABLE: pi-todo does not own an active session");
266
266
  }
267
267
  const sessionId = ctx.sessionManager.getSessionId(),
268
- leaf = ctx.sessionManager.getLeafId(),
269
268
  before = branchSnapshot(ctx.sessionManager.getBranch());
269
+ let leaf = ctx.sessionManager.getLeafId();
270
270
  TaskProvider.#importScope(ctx, before);
271
271
  return {
272
- append: (customType: string, list: TodoList): void => {
272
+ append: (customType: string, data: TodoList | TodoDelta, list: TodoList): void => {
273
273
  if (
274
274
  ctx.sessionManager.getSessionId() !== sessionId ||
275
275
  ctx.sessionManager.getLeafId() !== leaf
@@ -277,7 +277,8 @@ class TaskProvider {
277
277
  throw new Error("STALE_ORIGIN: session branch changed during task mutation");
278
278
  }
279
279
  protect(before, list, [...this.#leases.values()]);
280
- this.#host.appendEntry(customType, list);
280
+ this.#host.appendEntry(customType, data);
281
+ leaf = ctx.sessionManager.getLeafId();
281
282
  },
282
283
  branch: () => ctx.sessionManager.getBranch(),
283
284
  sessionId,
@@ -1,11 +1,73 @@
1
1
  import type { SessionBoundaryDraft, SessionEntry } from "@earendil-works/pi-coding-agent";
2
- import { completionReminder, parse } from "./wasm.ts";
2
+ import type { ListFrame } from "./branch-state.ts";
3
3
  import type { ReminderFact } from "./wasm.ts";
4
- import { STATE_ENTRY } from "./state.ts";
4
+ import { branchList } from "./state.ts";
5
+ import { completionReminder } from "./wasm.ts";
5
6
 
6
7
  const REMINDER_ENTRY = "todo-reminder",
8
+ absent = -1,
9
+ first = 0,
10
+ step = 1;
11
+
12
+ /** Retains only the final list and progress since the last reminder. */
13
+ class ReminderHistory {
14
+ readonly #facts: ReminderFact[] = [];
15
+ #latest: ListFrame | undefined = undefined;
16
+ #progress = false;
17
+ #lastReminder = absent;
18
+
19
+ public boundary(kind: "user" | "reminder"): void {
20
+ this.#facts.push({ kind });
21
+ this.#lastReminder = kind === "user" ? absent : this.#facts.length - step;
22
+ this.#progress = false;
23
+ }
24
+
25
+ public snapshot(frame: ListFrame): void {
26
+ this.#latest = frame;
27
+ this.#progress ||= frame.progress;
28
+ }
29
+
30
+ public facts(): ReminderFact[] {
31
+ if (this.#latest !== undefined) {
32
+ const snapshot: ReminderFact = { kind: "snapshot", list: this.#latest.list };
33
+ if (this.#lastReminder >= first && !this.#progress) {
34
+ this.#facts.splice(this.#lastReminder, first, snapshot);
35
+ } else {
36
+ this.#facts.push(snapshot);
37
+ }
38
+ }
39
+ return this.#facts;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Reduces branch history without materializing intermediate delta lists.
45
+ * @param {readonly SessionEntry[]} branch Persisted entries.
46
+ * @param {readonly SessionBoundaryDraft[]} drafts Proposed entries.
47
+ * @returns {ReminderFact[]} Equivalent reminder facts with only the final list.
48
+ */
49
+ const reminderFacts = (
50
+ branch: readonly SessionEntry[],
51
+ drafts: readonly SessionBoundaryDraft[],
52
+ ): ReminderFact[] => {
53
+ const history = new ReminderHistory(),
54
+ entries = [...branch, ...drafts],
55
+ frames = branchList(entries);
56
+ let next = frames.next();
57
+ for (const entry of entries) {
58
+ if (entry.type === "message" && entry.message.role === "user") {
59
+ history.boundary("user");
60
+ } else if (next.done !== true && next.value.entry === entry) {
61
+ history.snapshot(next.value);
62
+ next = frames.next();
63
+ } else if (entry.type === "custom_message" && entry.customType === REMINDER_ENTRY) {
64
+ history.boundary("reminder");
65
+ }
66
+ }
67
+ return history.facts();
68
+ },
7
69
  /**
8
- * Projects pi's branch and boundary drafts into core-owned reminder facts.
70
+ * Requests the next reminder from the core.
9
71
  * @param {readonly SessionEntry[]} branch Persisted branch entries.
10
72
  * @param {readonly SessionBoundaryDraft[]} drafts Proposed boundary entries.
11
73
  * @returns {string | undefined} The next reminder, when permitted.
@@ -13,18 +75,6 @@ const REMINDER_ENTRY = "todo-reminder",
13
75
  reminder = (
14
76
  branch: readonly SessionEntry[],
15
77
  drafts: readonly SessionBoundaryDraft[],
16
- ): string | undefined => {
17
- const facts: ReminderFact[] = [];
18
- for (const entry of [...branch, ...drafts]) {
19
- if (entry.type === "message" && entry.message.role === "user") {
20
- facts.push({ kind: "user" });
21
- } else if (entry.type === "custom" && entry.customType === STATE_ENTRY) {
22
- facts.push({ kind: "snapshot", list: parse(entry.data) });
23
- } else if (entry.type === "custom_message" && entry.customType === REMINDER_ENTRY) {
24
- facts.push({ kind: "reminder" });
25
- }
26
- }
27
- return completionReminder({ facts });
28
- };
78
+ ): string | undefined => completionReminder({ facts: reminderFacts(branch, drafts) });
29
79
 
30
- export { REMINDER_ENTRY, reminder };
80
+ export { REMINDER_ENTRY, reminder, reminderFacts };
@@ -0,0 +1,59 @@
1
+ import { DELTA_ENTRY, STATE_ENTRY, branchSnapshot } from "./state.ts";
2
+ import { apply, completionReminder, importUnit, imported } from "./wasm.ts";
3
+ import { entry, taskAt } from "./delta-fixture.ts";
4
+ import { referenceFacts, referenceSnapshot } from "./snapshot-reference-fixture.ts";
5
+ import { firstId } from "./contract-fixture.ts";
6
+ import { leafTask } from "./delta.ts";
7
+ import { reminderFacts } from "./reminder.ts";
8
+ import { worker } from "./provider-fixture.ts";
9
+
10
+ const sealReference = async (): Promise<{ actual: unknown; expected: unknown; seal: unknown }> => {
11
+ const source = await worker("github.com/oisin-ee/oisinpi");
12
+ try {
13
+ const seed = JSON.stringify({
14
+ binding: source.claimed.binding,
15
+ execution: source.claimed.binding.execution,
16
+ exported: source.claimed.exported,
17
+ version: 1,
18
+ }),
19
+ importedList = importUnit(
20
+ { tasks: [] },
21
+ seed,
22
+ "worker-session",
23
+ "github.com/oisin-ee/oisinpi",
24
+ ).list,
25
+ branch = [entry("import", STATE_ENTRY, importedList)],
26
+ full = [entry("import", STATE_ENTRY, importedList)],
27
+ unitId = firstId(importedList),
28
+ sealed = apply(
29
+ branchSnapshot(branch),
30
+ { evidence: "All unit checks pass", op: "done", task: unitId },
31
+ { mutationId: "seal", sessionId: "worker-session" },
32
+ ).list,
33
+ delta = {
34
+ changed: [{ id: unitId, task: leafTask(taskAt(sealed)) }],
35
+ orders: [],
36
+ removed: [],
37
+ version: 1,
38
+ };
39
+ branch.push(entry("seal", DELTA_ENTRY, delta), entry("repeat", DELTA_ENTRY, delta));
40
+ full.push(entry("seal", STATE_ENTRY, sealed), entry("repeat", STATE_ENTRY, sealed));
41
+ return {
42
+ actual: {
43
+ facts: completionReminder({ facts: reminderFacts(branch, []) }),
44
+ list: branchSnapshot(branch),
45
+ reference: taskAt(branchSnapshot(branch)).unit?.reference,
46
+ },
47
+ expected: {
48
+ facts: completionReminder({ facts: referenceFacts(full) }),
49
+ list: referenceSnapshot(full),
50
+ reference: source.claimed.binding.contract,
51
+ },
52
+ seal: imported(branchSnapshot(branch), "worker-session")?.seal,
53
+ };
54
+ } finally {
55
+ source.test.session.dispose();
56
+ }
57
+ };
58
+
59
+ export { sealReference };
@@ -0,0 +1,88 @@
1
+ import type { ExecutionRef, ReminderFact, TodoList, UnitRef } from "./wasm.ts";
2
+ import { REMINDER_ENTRY } from "./reminder.ts";
3
+ import { STATE_ENTRY } from "./state.ts";
4
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
5
+ import { parse } from "./wasm.ts";
6
+
7
+ // The full-snapshot implementation before deltas, retained as the independent oracle.
8
+ const originFor = (
9
+ reference: Readonly<UnitRef>,
10
+ entryId: string,
11
+ origins: Readonly<Map<string, string>>,
12
+ ): string => {
13
+ const key = JSON.stringify([reference.sessionId, reference.unitId, reference.revision]),
14
+ origin = origins.get(key) ?? entryId;
15
+ origins.set(key, origin);
16
+ return origin;
17
+ };
18
+ class ReferenceProvenance {
19
+ readonly #origins = new Map<string, string>();
20
+ readonly #seals = new Map<string, string>();
21
+
22
+ public resolve(
23
+ unit: {
24
+ readonly reference: Readonly<UnitRef>;
25
+ readonly imported:
26
+ | {
27
+ readonly seed: { readonly execution: Readonly<ExecutionRef> };
28
+ readonly seal: { readonly entryId: string } | undefined;
29
+ }
30
+ | undefined;
31
+ },
32
+ entryId: string,
33
+ ): void {
34
+ if (unit.imported === undefined) {
35
+ Object.assign(unit.reference, {
36
+ contractEntryId: originFor(unit.reference, entryId, this.#origins),
37
+ });
38
+ } else if (unit.imported.seal !== undefined) {
39
+ const key = JSON.stringify(unit.imported.seed.execution),
40
+ sealEntry = this.#seals.get(key) ?? entryId;
41
+ this.#seals.set(key, sealEntry);
42
+ Object.assign(unit.imported.seal, { entryId: sealEntry });
43
+ }
44
+ }
45
+ }
46
+ const referenceSnapshot = (branch: readonly SessionEntry[]): TodoList => {
47
+ const provenance = new ReferenceProvenance();
48
+ let current: TodoList = { tasks: [] };
49
+ for (const entry of branch.filter(
50
+ (candidate) => candidate.type === "custom" && candidate.customType === STATE_ENTRY,
51
+ )) {
52
+ if (entry.type === "custom") {
53
+ current = parse(entry.data);
54
+ for (const task of current.tasks.flatMap((root) => [root, ...(root.subtasks ?? [])])) {
55
+ if (task.unit !== undefined) {
56
+ provenance.resolve(
57
+ { imported: task.unit.imported, reference: task.unit.reference },
58
+ entry.id,
59
+ );
60
+ }
61
+ }
62
+ }
63
+ }
64
+ return current;
65
+ },
66
+ referenceLatest = (branch: readonly SessionEntry[]): unknown => {
67
+ for (const entry of branch.toReversed()) {
68
+ if (entry.type === "custom" && entry.customType === STATE_ENTRY) {
69
+ return entry.data;
70
+ }
71
+ }
72
+ return { tasks: [] };
73
+ },
74
+ referenceFacts = (branch: readonly SessionEntry[]): ReminderFact[] => {
75
+ const facts: ReminderFact[] = [];
76
+ for (const entry of branch) {
77
+ if (entry.type === "message" && entry.message.role === "user") {
78
+ facts.push({ kind: "user" });
79
+ } else if (entry.type === "custom" && entry.customType === STATE_ENTRY) {
80
+ facts.push({ kind: "snapshot", list: parse(entry.data) });
81
+ } else if (entry.type === "custom_message" && entry.customType === REMINDER_ENTRY) {
82
+ facts.push({ kind: "reminder" });
83
+ }
84
+ }
85
+ return facts;
86
+ };
87
+
88
+ export { referenceFacts, referenceLatest, referenceSnapshot };