pi-braid 0.43.27 → 0.43.29

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,223 @@
1
+ /**
2
+ * What the session-start journal pointer says about work still open.
3
+ *
4
+ * The pointer used to be built from a line count alone, so a journal holding a
5
+ * pending install and a journal holding forty closed outcomes printed the same
6
+ * sentence: the seat beginning the day could not tell that something was
7
+ * waiting for it. Naming the open intents costs a sentence in the first prompt
8
+ * of every session, so the whole text keeps a fixed ceiling and gives up detail
9
+ * in a fixed order instead of growing with the journal.
10
+ *
11
+ * Reading is line-level: an entry counts when its `kind` is `intent` and its
12
+ * `status` is `open`. The digest printer derives a subject's status across
13
+ * supersession chains and stays the authority on the full program, so a name
14
+ * here can be an intent a later line retired; against this project's journal
15
+ * when the pointer was written, five of the seven open-status intents were
16
+ * already retired that way. The trade is deliberate and the digest is where a
17
+ * seat confirms what is live: naming work already closed costs a line of
18
+ * attention, while hiding an install nobody was told about is the failure this
19
+ * pointer exists to repair. Honoring the journal's own `supersedes` edges is
20
+ * what would narrow it, and that is one line of selection, not one of wording.
21
+ */
22
+
23
+ /** Ceiling for the whole pointer text. A line delivered into every session is
24
+ * paid for by every turn that follows it, so the cost is per session, not per
25
+ * journal entry. */
26
+ export const JOURNAL_PRIOR_BUDGET = 480;
27
+
28
+ /** Named intents in the text; the rest are counted. Three subjects are about as
29
+ * many as a reader can carry into the work they were about to start. */
30
+ const NAMED_INTENT_LIMIT = 3;
31
+
32
+ /** Longest subject rendered. The journal writer admits slugs up to 64
33
+ * characters, so one hostile line would otherwise spend the budget alone. */
34
+ const SUBJECT_LIMIT = 32;
35
+
36
+ const HOUR_MS = 3_600_000;
37
+
38
+ const DIGEST_COMMAND = "packages/core/scripts/check-journal.mjs --digest";
39
+
40
+ /** The closing sentence of the pointer when nothing is open. Shown to every
41
+ * session, so it keeps its exact words. */
42
+ const DIGEST_POINTER = `Read the open program before acting (digest printer: ${DIGEST_COMMAND}), so a decision gets superseded, not rediscovered.`;
43
+
44
+ /** The same printer, said shorter: naming what is open already answers the
45
+ * question the long form motivates, and the room it frees is what pays for
46
+ * the names. */
47
+ const DIGEST_POINTER_SHORT = `Full program: ${DIGEST_COMMAND}.`;
48
+
49
+ const CLOSE_SINGLE = "Run the install it names, or close it with the reason it will not run.";
50
+ const CLOSE_PLURAL = "Run the install each names, or close it with the reason it will not run.";
51
+
52
+ /** What the pointer needs from the handler: the line count it always printed,
53
+ * and the path it names. */
54
+ export interface JournalPointerFacts {
55
+ count: number;
56
+ journalFile: string;
57
+ }
58
+
59
+ /** One intent whose `status` says `open`. */
60
+ export interface OpenIntent {
61
+ subject: string;
62
+ /** Whole hours since the entry's own `at`; null when that stamp is unusable,
63
+ * which is reported as no age rather than as a guess. */
64
+ ageHours: number | null;
65
+ /** The entry's `expires_at`, kept only when it parses. A broken stamp is a
66
+ * missing detail, never a reason to hide the intent behind it. */
67
+ expiresAt: string | null;
68
+ expired: boolean;
69
+ }
70
+
71
+ /**
72
+ * The journal lines that name open work.
73
+ *
74
+ * Anything unreadable is skipped: a line that is not JSON, a value that is not
75
+ * an object, an entry without a usable `subject`, and an `expires_at` that does
76
+ * not parse (the stamp is dropped, the intent is not). A journal is written by
77
+ * a different process and edited by hand, so a reader that throws on the first
78
+ * malformed line would take the whole session-start bundle down with it.
79
+ */
80
+ export function selectOpenIntents(journalText: string, now: Date): OpenIntent[] {
81
+ const open: OpenIntent[] = [];
82
+ for (const line of journalText.split("\n")) {
83
+ if (!line.trim()) continue;
84
+ const entry = parseEntry(line);
85
+ if (!entry) continue;
86
+ if (entry.kind !== "intent" || entry.status !== "open") continue;
87
+ const subject = typeof entry.subject === "string" ? entry.subject.trim() : "";
88
+ if (!subject) continue;
89
+
90
+ const writtenAt = typeof entry.at === "string" ? Date.parse(entry.at) : Number.NaN;
91
+ const expiresAt =
92
+ typeof entry.expires_at === "string" ? Date.parse(entry.expires_at) : Number.NaN;
93
+
94
+ open.push({
95
+ subject,
96
+ ageHours: Number.isNaN(writtenAt)
97
+ ? null
98
+ : Math.max(0, Math.floor((now.getTime() - writtenAt) / HOUR_MS)),
99
+ expiresAt: Number.isNaN(expiresAt) ? null : (entry.expires_at as string),
100
+ expired: !Number.isNaN(expiresAt) && expiresAt < now.getTime(),
101
+ });
102
+ }
103
+ // The intent whose window already closed is the one a reader has to act on,
104
+ // so it is named before the rest; journal order stands inside each group.
105
+ return [...open.filter((intent) => intent.expired), ...open.filter((intent) => !intent.expired)];
106
+ }
107
+
108
+ /**
109
+ * The journal pointer, complete: the sentence this step has always printed,
110
+ * extended with what is open.
111
+ *
112
+ * With nothing open the result is the original text byte for byte. With work
113
+ * open the count-and-path sentence is kept and the digest printer is restated
114
+ * in its short form: with a 91-character journal path the long form plus one
115
+ * expired intent is 527 characters against the 480 ceiling, and the sentence
116
+ * that motivates reading the journal is the one with room to yield.
117
+ */
118
+ export function journalPriorText(
119
+ facts: JournalPointerFacts,
120
+ journalText: string,
121
+ now: Date,
122
+ ): string {
123
+ const intro = journalIntro(facts);
124
+ const open = selectOpenIntents(journalText, now);
125
+ if (open.length === 0) return `${intro} ${DIGEST_POINTER}`;
126
+
127
+ // Detail is given up in order of what a reader needs it for: the name of a
128
+ // waiting install, then the moment its window closes, then the standing
129
+ // pointer to the full program, then the count alone. Dropping the names to
130
+ // keep the pointer would save the cheaper fact and hide the dearer one.
131
+ const ladder = [
132
+ `${intro} ${describeOpen(open, "stamped")} ${DIGEST_POINTER_SHORT}`,
133
+ `${intro} ${describeOpen(open, "plain")} ${DIGEST_POINTER_SHORT}`,
134
+ `${intro} ${describeOpen(open, "stamped")}`,
135
+ `${intro} ${describeOpen(open, "plain")}`,
136
+ `${intro} ${countedSentence(open)} ${DIGEST_POINTER_SHORT}`,
137
+ `${intro} ${countedSentence(open)}`,
138
+ `${intro} ${open.length} open intent${open.length === 1 ? "" : "s"}.`,
139
+ ];
140
+ // Richest description that fits. The last rung is printed rather than
141
+ // dropped when nothing fits: a journal path long enough to spend the ceiling
142
+ // alone is a reason to say less, never a reason to leave a pending install
143
+ // unmentioned.
144
+ return ladder.find((text) => text.length < JOURNAL_PRIOR_BUDGET) ?? ladder[ladder.length - 1];
145
+ }
146
+
147
+ function journalIntro({ count, journalFile }: JournalPointerFacts): string {
148
+ return (
149
+ `The project journal holds ${count} entr${count === 1 ? "y" : "ies"} at ${journalFile} -- ` +
150
+ `what earlier seats decided and why, readable without their sessions.`
151
+ );
152
+ }
153
+
154
+ type Detail = "stamped" | "plain" | "counted";
155
+
156
+ function describeOpen(open: OpenIntent[], detail: Detail): string {
157
+ if (detail === "counted") return countedSentence(open);
158
+ const withStamp = detail === "stamped";
159
+ return open.length === 1 ? singleSentence(open[0], withStamp) : listSentence(open, withStamp);
160
+ }
161
+
162
+ /** One open intent reads as a sentence: a list of one is a fragment, and the
163
+ * instruction that follows it addresses a single install. */
164
+ function singleSentence(intent: OpenIntent, withStamp: boolean): string {
165
+ const opening = intent.expired
166
+ ? "One intent is still open and EXPIRED"
167
+ : "One intent is still open";
168
+ return `${opening}: ${named(intent)}${roundStamp(intent, withStamp)}. ${CLOSE_SINGLE}`;
169
+ }
170
+
171
+ function listSentence(open: OpenIntent[], withStamp: boolean): string {
172
+ const items = open.slice(0, NAMED_INTENT_LIMIT).map((intent) => listItem(intent, withStamp));
173
+ const rest = open.length - Math.min(open.length, NAMED_INTENT_LIMIT);
174
+ const more = rest > 0 ? `; +${rest} more open` : "";
175
+ return `Open intents: ${items.join("; ")}${more}. ${CLOSE_PLURAL}`;
176
+ }
177
+
178
+ /** The expired marker stays in the lean form: it is the fact a reader acts on,
179
+ * while the exact moment is one the digest can restate. */
180
+ function listItem(intent: OpenIntent, withStamp: boolean): string {
181
+ const expired = intent.expired ? ", EXPIRED" : "";
182
+ if (!withStamp || intent.expiresAt === null) return `${named(intent)}${expired}`;
183
+ return intent.expired
184
+ ? `${named(intent)}, EXPIRED (expires_at ${intent.expiresAt})`
185
+ : `${named(intent)}, expires ${intent.expiresAt}`;
186
+ }
187
+
188
+ /** In the single sentence the opening clause already carries the EXPIRED word,
189
+ * so this adds the moment alone. */
190
+ function roundStamp(intent: OpenIntent, withStamp: boolean): string {
191
+ if (!withStamp || intent.expiresAt === null) return "";
192
+ return intent.expired ? ` (expires_at ${intent.expiresAt})` : ` (expires ${intent.expiresAt})`;
193
+ }
194
+
195
+ function countedSentence(open: OpenIntent[]): string {
196
+ const expired = open.filter((intent) => intent.expired).length;
197
+ const ages = open
198
+ .map((intent) => intent.ageHours)
199
+ .filter((hours): hours is number => hours !== null);
200
+ const oldest = ages.length > 0 ? `, oldest ${Math.max(...ages)}h old` : "";
201
+ const lapsed = expired > 0 ? `, ${expired} EXPIRED` : "";
202
+ const count = `${open.length} open intent${open.length === 1 ? "" : "s"} in this journal`;
203
+ return `${count}${oldest}${lapsed}. ${open.length === 1 ? CLOSE_SINGLE : CLOSE_PLURAL}`;
204
+ }
205
+
206
+ function named(intent: OpenIntent): string {
207
+ const age = intent.ageHours === null ? "" : ` ${intent.ageHours}h old`;
208
+ return `"${clipSubject(intent.subject)}"${age}`;
209
+ }
210
+
211
+ function clipSubject(subject: string): string {
212
+ return subject.length <= SUBJECT_LIMIT ? subject : `${subject.slice(0, SUBJECT_LIMIT - 1)}…`;
213
+ }
214
+
215
+ function parseEntry(line: string): Record<string, unknown> | null {
216
+ try {
217
+ const value: unknown = JSON.parse(line);
218
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
219
+ return value as Record<string, unknown>;
220
+ } catch {
221
+ return null;
222
+ }
223
+ }
@@ -53,6 +53,7 @@ import {
53
53
  } from "../../../lib/config/braid-paths.js";
54
54
  import { projectSlugFromCwd } from "../../memory/scratchpad/persistence.js";
55
55
  import { readResumeScratchpadState } from "../resume-state.js";
56
+ import { journalPriorText } from "./open-intents.js";
56
57
 
57
58
  const log = createLogger("enforcement:session-start-discoverability");
58
59
 
@@ -225,22 +226,20 @@ export function registerSessionStartDiscoverability(pi: ExtensionAPI): void {
225
226
  // 7. The owner-input journal. The path comes from the constant the
226
227
  // writer appends through, never a hand-built shape: two spellings for
227
228
  // one file is how the scratchpad pointer armed itself against a file
228
- // nothing writes (see step 1).
229
+ // nothing writes (see step 1). The text is composed in `open-intents`,
230
+ // which also names the intents whose status says open: a journal holding
231
+ // a pending install printed the same count sentence as one holding forty
232
+ // closed outcomes, so the seat could not see that work was waiting.
229
233
  try {
230
234
  const slug = projectSlugFromCwd(cwd);
231
235
  const journalFile = journalFilePath(slug);
232
236
  if (existsSync(journalFile)) {
233
- const count = readFileSync(journalFile, "utf-8")
234
- .split("\n")
235
- .filter((line) => line.trim()).length;
237
+ const journalText = readFileSync(journalFile, "utf-8");
238
+ const count = journalText.split("\n").filter((line) => line.trim()).length;
236
239
  if (count > 0) {
237
240
  signals.push({
238
241
  type: "journal_prior",
239
- text:
240
- `The project journal holds ${count} entr${count === 1 ? "y" : "ies"} at ${journalFile} -- ` +
241
- `what earlier seats decided and why, readable without their sessions. ` +
242
- `Read the open program before acting (digest printer: packages/core/scripts/check-journal.mjs --digest), ` +
243
- `so a decision gets superseded, not rediscovered.`,
242
+ text: journalPriorText({ count, journalFile }, journalText, new Date()),
244
243
  });
245
244
  }
246
245
  }
@@ -63,6 +63,14 @@ import {
63
63
  type WorkerStats,
64
64
  type PopulationRead,
65
65
  } from "../../lib/orchestrator/index.js";
66
+ // The queue-fact readers come from their module directly: the barrel above is
67
+ // one way into the library, not the only one, and it does not re-export these.
68
+ import {
69
+ normalizeDependsOn,
70
+ orderWorkerRows,
71
+ validateDependencies,
72
+ type WorkerOrderRow,
73
+ } from "../../lib/orchestrator/workers.js";
66
74
 
67
75
  const log = createLogger("orchestrator");
68
76
 
@@ -454,11 +462,28 @@ function textResult(text: string, details: Record<string, unknown> = {}) {
454
462
  /** One-line registry listing for a worker entry. */
455
463
  function workerLine(entry: WorkerEntry): string {
456
464
  const closed = entry.closedAt ? ` closed=${entry.closedAt}` : "";
465
+ // Printed only when the row carries one: an unranked, wait-free row keeps the
466
+ // line it had before the queue facts existed.
467
+ const priority = typeof entry.priority === "number" ? ` priority=${entry.priority}` : "";
468
+ const dependsOn =
469
+ Array.isArray(entry.dependsOn) && entry.dependsOn.length > 0
470
+ ? ` depends-on=${entry.dependsOn.join(", ")}`
471
+ : "";
457
472
  return ` ${entry.workerId} spec=${entry.spec} status=${entry.status} pane=${
458
473
  entry.pane ?? "-"
459
474
  } session=${entry.workerSession ?? "-"} output=${
460
475
  entry.outputFile ?? "-"
461
- } branch=${entry.branch ?? "-"}${closed}`;
476
+ } branch=${entry.branch ?? "-"}${closed}${priority}${dependsOn}`;
477
+ }
478
+
479
+ /**
480
+ * One listing entry: the row line, plus the ids holding it after it, indented
481
+ * under the row so the marker can never be read as a row of its own.
482
+ */
483
+ function workerListLine(row: WorkerOrderRow): string {
484
+ const line = workerLine(row.entry);
485
+ if (row.blockedBy.length === 0) return line;
486
+ return `${line}\n blocked-by: ${row.blockedBy.join(", ")}`;
462
487
  }
463
488
 
464
489
  /**
@@ -488,6 +513,8 @@ function formatCheckVerdict(verdict: WorkerCheckResult): string {
488
513
  return [
489
514
  `Worker ${verdict.workerId}`,
490
515
  `status: ${verdict.status}`,
516
+ `storedStatus: ${verdict.storedStatus}`,
517
+ `blockedBy: ${verdict.blockedBy.length > 0 ? verdict.blockedBy.join(", ") : "-"}`,
491
518
  `reason: ${verdict.reason}`,
492
519
  `outputFile: ${verdict.outputFile ?? "-"} (${age})`,
493
520
  `sessionGrowthAgeSec: ${verdict.sessionGrowthAgeSec ?? "-"}`,
@@ -648,6 +675,25 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
648
675
  description: "Lifecycle status for update-worker (see the tool description).",
649
676
  }),
650
677
  ),
678
+ priority: Type.Optional(
679
+ // `{ anyOf: [{ type: "number" }, { type: "null" }] }` written as its own
680
+ // keywords: the builder's named constructors have no null literal, and the
681
+ // schema this hand-built object emits is plain JSON Schema.
682
+ Type.Unsafe<number | null>({
683
+ anyOf: [{ type: "number" }, { type: "null" }],
684
+ description:
685
+ "Queue rank: lower runs sooner; null is unranked, which sorts after every ranked row. " +
686
+ "spawn-worker/register-worker record it at admission; update-worker changes or clears it.",
687
+ }),
688
+ ),
689
+ dependsOn: Type.Optional(
690
+ Type.Array(Type.String(), {
691
+ description:
692
+ "Worker ids this row waits for (spawn-worker/register-worker only: dependencies are fixed at admission). " +
693
+ "Refused when an id is unknown, is this worker's own id, or would close a loop; a refused admission writes nothing. " +
694
+ "check-worker reports `blocked`, naming these ids, while any of them is not merged or completed.",
695
+ }),
696
+ ),
651
697
  phase: Type.Optional(
652
698
  Type.String({
653
699
  description:
@@ -729,6 +775,8 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
729
775
  workspace?: string;
730
776
  workerSession?: string;
731
777
  status?: string;
778
+ priority?: number | null;
779
+ dependsOn?: string[];
732
780
  phase?: string;
733
781
  lastStep?: string;
734
782
  requestId?: string;
@@ -756,6 +804,8 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
756
804
  workspace,
757
805
  workerSession,
758
806
  status,
807
+ priority,
808
+ dependsOn,
759
809
  phase,
760
810
  lastStep,
761
811
  requestId,
@@ -790,8 +840,16 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
790
840
  // live row for one worker. A different request, or the same id
791
841
  // describing different work, is refused with both ids named.
792
842
  const effectiveRequestId = resolveRequestId(workerId, requestId);
793
- const existing = readWorkers(projectCwd).workers[workerId];
794
- const decision = decideAdmission(existing, effectiveRequestId, { spec, files });
843
+ const registryAtSpawn = readWorkers(projectCwd);
844
+ const existing = registryAtSpawn.workers[workerId];
845
+ // Dependencies are part of what the work is, so a retry carries the same
846
+ // set; changing them under the same request id is different work.
847
+ const dependsOnIds = normalizeDependsOn(dependsOn);
848
+ const decision = decideAdmission(existing, effectiveRequestId, {
849
+ spec,
850
+ files,
851
+ dependsOn: dependsOnIds,
852
+ });
795
853
  if (decision.action === "reuse" && decision.entry) {
796
854
  return textResult(reuseReport(decision.entry, effectiveRequestId), {
797
855
  entry: decision.entry,
@@ -806,6 +864,13 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
806
864
  throw new Error(`spawn-worker: ${decision.reason}.`);
807
865
  }
808
866
 
867
+ // A dependency that cannot be satisfied refuses the spawn before a
868
+ // branch or a lock exists, so a refused spawn leaves nothing to undo.
869
+ const dependencyRefusal = validateDependencies(workerId, dependsOnIds, registryAtSpawn);
870
+ if (dependencyRefusal) {
871
+ throw new Error(`spawn-worker: ${dependencyRefusal.message}.`);
872
+ }
873
+
809
874
  const conflicts = filesHeldByOthers(files, workerId, repoRoot);
810
875
  if (conflicts.length > 0) {
811
876
  return textResult(
@@ -834,6 +899,8 @@ const orchestrateTool: ToolDefinition<any, any, any> = {
834
899
  files,
835
900
  branch: branchName,
836
901
  outputFile,
902
+ priority,
903
+ dependsOn: dependsOnIds,
837
904
  requestId: effectiveRequestId,
838
905
  },
839
906
  projectCwd,
@@ -913,6 +980,8 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
913
980
  files,
914
981
  branch,
915
982
  outputFile,
983
+ priority,
984
+ dependsOn,
916
985
  pane,
917
986
  workerSession,
918
987
  requestId,
@@ -945,6 +1014,8 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
945
1014
  files,
946
1015
  branch,
947
1016
  outputFile,
1017
+ priority,
1018
+ dependsOn,
948
1019
  pane,
949
1020
  workerSession,
950
1021
  requestId,
@@ -959,6 +1030,14 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
959
1030
  if (!workerId) {
960
1031
  throw new Error("update-worker requires workerId");
961
1032
  }
1033
+ if (dependsOn !== undefined) {
1034
+ throw new Error(
1035
+ "update-worker: dependencies are fixed at admission — dependsOn is admitted by " +
1036
+ "spawn-worker/register-worker only. A worker that gains a dependency after it " +
1037
+ "started is a second unit of work wearing the first one's id; close the entry and " +
1038
+ "admit it again.",
1039
+ );
1040
+ }
962
1041
 
963
1042
  const patch: UpdateWorkerPatch = {};
964
1043
  if (pane !== undefined) patch.pane = pane;
@@ -968,6 +1047,7 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
968
1047
  if (branch !== undefined) patch.branch = branch;
969
1048
  if (files !== undefined) patch.files = files;
970
1049
  if (status !== undefined) patch.status = parseWorkerStatus(status);
1050
+ if (priority !== undefined) patch.priority = priority;
971
1051
  if (phase !== undefined || lastStep !== undefined) {
972
1052
  if (!phase || !lastStep) {
973
1053
  throw new Error(
@@ -1031,7 +1111,10 @@ When the worker signals completion, use orchestrate action=verify-and-merge to r
1031
1111
  const closedCount = all.filter((entry) => entry.closedAt).length;
1032
1112
  const byStatus = WORKER_STATUSES.map((s) => `${s}=${counts.get(s) ?? 0}`).join(" ");
1033
1113
 
1034
- const lines = shown.map(workerLine).join("\n");
1114
+ // Actionable order over the rows being shown, with satisfaction read
1115
+ // against every row: a closed dependency still counts as delivered.
1116
+ const ordered = orderWorkerRows(shown, registry);
1117
+ const lines = [...ordered.ready, ...ordered.blocked].map(workerListLine).join("\n");
1035
1118
  return textResult(
1036
1119
  `Workers (${repoRoot ?? process.cwd()}):\n${lines}\ncounts: total=${all.length} live=${
1037
1120
  all.length - closedCount