owenloop 0.4.1 → 0.5.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 (154) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +58 -31
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{cli.d.ts → src/cli.d.ts} +18 -3
  109. package/dist/{cli.js → src/cli.js} +770 -114
  110. package/dist/{credentials.d.ts → src/credentials.d.ts} +18 -12
  111. package/dist/{credentials.js → src/credentials.js} +14 -12
  112. package/dist/{defs.js → src/defs.js} +36 -36
  113. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  114. package/dist/{engine.js → src/engine.js} +14 -14
  115. package/dist/{hub.d.ts → src/hub.d.ts} +205 -10
  116. package/dist/{hub.js → src/hub.js} +370 -12
  117. package/dist/{index.d.ts → src/index.d.ts} +1 -1
  118. package/dist/{index.js → src/index.js} +1 -1
  119. package/dist/{mcp → src/mcp}/serve.d.ts +5 -4
  120. package/dist/{mcp → src/mcp}/serve.js +168 -31
  121. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  122. package/dist/{mcp → src/mcp}/server.js +6 -9
  123. package/dist/{model.js → src/model.js} +1 -1
  124. package/dist/{types.d.ts → src/types.d.ts} +18 -18
  125. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  126. package/dist/{util.js → src/util.js} +3 -2
  127. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  128. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  129. package/docs/authoring.md +93 -53
  130. package/docs/cli.md +597 -76
  131. package/docs/design.md +33 -33
  132. package/docs/embedding.md +10 -9
  133. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  134. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  135. package/examples/workflows/judges/gate-sharpness.md +39 -0
  136. package/examples/workflows/judges/security.md +34 -0
  137. package/package.json +17 -8
  138. /package/dist/{add.d.ts → src/add.d.ts} +0 -0
  139. /package/dist/{add.js → src/add.js} +0 -0
  140. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  141. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  142. /package/dist/{factory.js → src/factory.js} +0 -0
  143. /package/dist/{lock.d.ts → src/lock.d.ts} +0 -0
  144. /package/dist/{lock.js → src/lock.js} +0 -0
  145. /package/dist/{model.d.ts → src/model.d.ts} +0 -0
  146. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  147. /package/dist/{paths.js → src/paths.js} +0 -0
  148. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  149. /package/dist/{schema.js → src/schema.js} +0 -0
  150. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  151. /package/dist/{store.js → src/store.js} +0 -0
  152. /package/dist/{types.js → src/types.js} +0 -0
  153. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  154. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -0,0 +1,163 @@
1
+ /** Where a step attempt is in its life. */
2
+ export type SessionStatus = 'active' | 'turn-ended' | 'submitted' | 'dead';
3
+ /** One line of `sessions.jsonl`. */
4
+ export interface SessionRecord {
5
+ workflow: string;
6
+ run: string;
7
+ step: string;
8
+ /** The composite `<workflow>/<run>` order id — the same string `hold --order`
9
+ * takes. Redundant with `workflow` + `run` by construction; kept because the
10
+ * contract lists it and Phase 6's `owenloop work sessions` display prints it.
11
+ * ALWAYS build it with `orderId()` so the two can never drift. */
12
+ order: string;
13
+ attempt: number;
14
+ /** Adapter id (`HarnessSessionRef.harness`). */
15
+ harness: string;
16
+ /** Provider-native session token (`HarnessSessionRef.token`). Machine-local. */
17
+ token: string;
18
+ cwd: string;
19
+ status: SessionStatus;
20
+ createdAt: number;
21
+ /**
22
+ * PHASE 4 — the reason watermark: the `at` of the NEWEST `ReasonEntry` already
23
+ * delivered into this session, by either a resume or a cold replay.
24
+ *
25
+ * The next re-offer filters `OrderPacket.owes[].reasons` to `at > this` and
26
+ * delivers only what is left, which is what makes a rejection cost a short
27
+ * delta instead of a whole brief.
28
+ *
29
+ * BACKWARD-COMPATIBLE BY CONSTRUCTION, no version bump and no migration:
30
+ * `isSessionRecord` validates only `workflow/run/step/harness/token/status` and
31
+ * carries every other field verbatim, so a record written before Phase 4 simply
32
+ * has no watermark. Absent reads as "nothing delivered yet", which makes the
33
+ * first resume after an upgrade deliver every reason — the safe direction to be
34
+ * wrong, since the alternative would silently swallow feedback.
35
+ *
36
+ * NOT part of the record key. The key stays `(workflow, run, step)` and
37
+ * `attempt` stays outside it, per Phase 1.
38
+ */
39
+ deliveredReasonAt?: number;
40
+ updatedAt: number;
41
+ }
42
+ export interface SessionStoreOptions {
43
+ /** Called once per skipped corrupt line. Default writes to stderr. */
44
+ warn?: (line: string) => void;
45
+ /** Compaction threshold in bytes, checked after each append. Default 2 MB. */
46
+ maxBytes?: number;
47
+ }
48
+ /** Default compaction threshold — plan §3's 2 MB. */
49
+ export declare const DEFAULT_MAX_BYTES = 2000000;
50
+ /** `<cacheDir>/sessions.jsonl`. */
51
+ export declare function sessionsPath(cacheDir: string): string;
52
+ /** The composite order id `<workflow>/<run>` — the one place it is built. */
53
+ export declare function orderId(workflow: string, run: string): string;
54
+ /**
55
+ * Every valid record in `file`, oldest first. A missing/unreadable file reads as
56
+ * `[]`. Blank lines are skipped silently; every other unusable line is skipped
57
+ * and reported through `warn` with its 1-indexed line number. Never throws.
58
+ */
59
+ export declare function readSessions(file: string, opts?: SessionStoreOptions): SessionRecord[];
60
+ /**
61
+ * The newest record for `(workflow, run, step)`, or `null` when the file is
62
+ * missing or holds no match. Scans forward and keeps the LAST match (last-wins).
63
+ * Side-effect-free — it never writes, never compacts, and never throws.
64
+ */
65
+ export declare function latestFor(file: string, workflow: string, run: string, step: string): SessionRecord | null;
66
+ /**
67
+ * Rewrite `file` with only the last record per `(workflow, run, step)`,
68
+ * preserving FIRST-SEEN key order, via temp file + rename. Corrupt lines are
69
+ * dropped in the process (they were already unreadable). A missing file is a
70
+ * no-op. Fs failures propagate here; `appendSession` is what swallows them.
71
+ */
72
+ export declare function compact(file: string, opts?: SessionStoreOptions): void;
73
+ /**
74
+ * PHASE 4 — retire every session of one RUN by appending a `dead` row per step.
75
+ *
76
+ * THE INVARIANT IT ENFORCES: session lifetime equals cwd lifetime. When the
77
+ * per-run work directory is removed, the work those sessions were revising is
78
+ * gone, so resuming into a freshly recreated (and empty) directory at the same
79
+ * path would hand the agent a conversation about files that no longer exist. The
80
+ * `prev.status !== 'dead'` precondition in `src/agent/loop.ts` is what refuses
81
+ * the resume; this function is what makes the status say `dead`.
82
+ *
83
+ * WHY A NEW ROW RATHER THAN A REWRITE: the store is append-only and last-wins per
84
+ * `(workflow, run, step)`, so appending a copy with `status: 'dead'` shadows the
85
+ * live row without rewriting history — and it keeps the ACCEPTED RACE in this
86
+ * module's header (compaction losing concurrent appends) as the only writer race.
87
+ *
88
+ * IDEMPOTENT: a key whose newest row is already `dead` is skipped, so a sweep
89
+ * that reaps the same run twice appends nothing the second time.
90
+ *
91
+ * SCOPE: the newest row per `(workflow, run, step)` for the given run, across
92
+ * EVERY step of that run — the work directory is per-run, so every step's session
93
+ * lived in it.
94
+ *
95
+ * FAILURE STANCE: `appendSession` PROPAGATES (see the header), and so does this.
96
+ * The caller — the work-directory reaper — must be able to see the failure,
97
+ * because retiring the sessions is a precondition of removing the directory, not
98
+ * a side note.
99
+ *
100
+ * Returns the step names actually marked, so a sweep can log a count.
101
+ */
102
+ export declare function markRunSessionsDead(file: string, workflow: string, run: string, now: number, opts?: SessionStoreOptions): string[];
103
+ /**
104
+ * PHASE 6, ITEM 4 — retire the `active` sessions of runs that are no longer
105
+ * running, so a crash or a reboot does not leave the store claiming a turn is in
106
+ * flight when no process exists.
107
+ *
108
+ * WHAT IS BROKEN WITHOUT THIS. `src/agent/loop.ts` writes `status: 'active'` when
109
+ * a turn starts and rewrites it at turn end. A worker killed mid-turn — SIGKILL,
110
+ * a panic, a reboot — never reaches the rewrite, so the newest row for that step
111
+ * says `active` forever. Nothing else ever corrects it.
112
+ *
113
+ * ── WHY THIS IS NOT `markRunSessionsDead` ────────────────────────────────────
114
+ *
115
+ * `markRunSessionsDead` retires EVERY non-`dead` newest row of a run. Reusing it
116
+ * here would destroy exactly the capability this phase has to keep working:
117
+ * `src/agent/loop.ts` refuses to resume a session whose previous status is
118
+ * `dead`, and a `turn-ended` or `submitted` row is a COMPLETED turn whose
119
+ * provider-side session is intact. A reboot does not invalidate one. Leaving
120
+ * those rows alone is precisely what "resume still works after a reboot" means.
121
+ *
122
+ * So ONLY `active` rows are eligible, and only for runs absent from
123
+ * `liveRunIds`.
124
+ *
125
+ * ── WHY RETIRING AN ORPHANED `active` ROW IS THE RIGHT DIRECTION TO BE WRONG ──
126
+ *
127
+ * An interrupted turn is the state you least want to resume into: the harness may
128
+ * have half-applied tool calls the worker has no record of, so a resumed session
129
+ * would carry a model that believes work happened which did not. The cost of
130
+ * retiring it is one cold replay. The cost of resuming it is silent divergence.
131
+ *
132
+ * ── KNOWN FALSE POSITIVE, STATED RATHER THAN ENGINEERED AROUND ───────────────
133
+ *
134
+ * An `owenloop work agent-run` started BY HAND, outside the shift, has no child record
135
+ * in the shift state dir, so a shift booting at that moment sees its `active` row
136
+ * as orphaned and retires it. The cost is one cold replay on a hand-run debugging
137
+ * session. Two things keep it small: the caller invokes this at BOOT only, which
138
+ * narrows the window to an instant, and every retirement is returned so the
139
+ * caller can log it with its `(workflow, run, step)`. Do NOT add a pid field to
140
+ * `SessionRecord` to close this — the record is deliberately machine-portable
141
+ * metadata, and the shift state dir is already the system of record for liveness.
142
+ *
143
+ * IDEMPOTENT: the rows it appends are `dead`, so a second call finds nothing
144
+ * `active` left and appends nothing.
145
+ *
146
+ * FAILURE STANCE: `appendSession` propagates, and so does this — same as
147
+ * `markRunSessionsDead`.
148
+ *
149
+ * @param liveRunIds run ids with a live `agent-run` child RIGHT NOW. A run in
150
+ * this set is skipped whatever its status.
151
+ * @returns the records that were retired, as they were BEFORE retirement, so the
152
+ * caller can log what it took away.
153
+ */
154
+ export declare function reconcileActiveSessions(file: string, liveRunIds: ReadonlySet<string>, now: number, opts?: SessionStoreOptions): SessionRecord[];
155
+ /**
156
+ * Append one record, then compact when the file has grown past `maxBytes`.
157
+ *
158
+ * The whole line is written in ONE `appendFileSync` call (with its trailing
159
+ * newline) so concurrent workers' O_APPEND writes interleave line-atomically on
160
+ * local filesystems. Append failures PROPAGATE — see this module's failure
161
+ * stance. The post-append compaction is best-effort and swallowed.
162
+ */
163
+ export declare function appendSession(file: string, rec: SessionRecord, opts?: SessionStoreOptions): void;
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Session store — the append-only JSONL record of which harness session belongs
3
+ * to which step attempt, so a rejected step can be RESUMED instead of restarted.
4
+ *
5
+ * Layout: one JSON object per line at `<cacheDir>/sessions.jsonl`
6
+ * (`sessionsPath`). The cache dir comes from the EXISTING `resolveCacheDir`
7
+ * (`src/bundle/cache.ts`); this phase adds NO new settings key.
8
+ *
9
+ * MACHINE-LOCAL BY DESIGN. A provider session token has no meaning off the
10
+ * machine that created it, so these records are NEVER sent to the hub —
11
+ * structurally guaranteed here by the absence of any `src/hub/` import, and
12
+ * socially by this comment. Nothing in this file talks to a network.
13
+ *
14
+ * LAST-WINS per `(workflow, run, step)`: a later line beats an earlier one.
15
+ * `attempt` is CARRIED BY the record and is deliberately NOT part of the key —
16
+ * a re-attempt appends a new record with the same key and a higher `attempt`,
17
+ * which correctly shadows the old one.
18
+ *
19
+ * FAILURE STANCE, three different answers on purpose:
20
+ * - READ is fail-open: a missing file reads as `[]` (mirrors `readChildRecords`
21
+ * in `src/shift/state.ts`), and a corrupt line is skipped and reported
22
+ * through the injectable `warn` callback, never thrown. A store that cannot
23
+ * be parsed must degrade a resume into a replay, not break the worker.
24
+ * - APPEND PROPAGATES. Unlike the shift's advisory metering records, a lost
25
+ * session token silently degrades a Phase 4 resume into a cold replay — real
26
+ * work thrown away — so the caller must see the failure.
27
+ * - COMPACTION is best-effort (swallowed): the un-compacted file is still
28
+ * correct, just larger.
29
+ *
30
+ * DEVIATION FROM PLAN §3, stated deliberately: plan §3 says "compact on load if
31
+ * > 2 MB". This module compacts on the WRITE path instead — `appendSession`
32
+ * appends, stats the file, and compacts past `maxBytes`. Reasons: `latestFor`
33
+ * stays side-effect-free (a read never becomes a writer, and never fails on a
34
+ * read-only filesystem), and a small `maxBytes` lets tests exercise compaction
35
+ * without writing 2 MB. The 2 MB default is unchanged.
36
+ *
37
+ * ACCEPTED RACE: `compact` reads, rewrites, and renames, so lines appended by
38
+ * another process in that window are lost. No locking is built. Session records
39
+ * are advisory — a lost token degrades that one step to the designed replay
40
+ * fallback — and compaction only runs past `maxBytes`.
41
+ *
42
+ * Logging follows the house rule (there are zero `console.*` calls anywhere in
43
+ * `src/`): the library takes an injectable callback and the default writes to
44
+ * stderr, so tests stay silent and assertable.
45
+ */
46
+ import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
47
+ import { join } from 'node:path';
48
+ const STATUSES = new Set(['active', 'turn-ended', 'submitted', 'dead']);
49
+ /** Default compaction threshold — plan §3's 2 MB. */
50
+ export const DEFAULT_MAX_BYTES = 2_000_000;
51
+ /** `<cacheDir>/sessions.jsonl`. */
52
+ export function sessionsPath(cacheDir) {
53
+ return join(cacheDir, 'sessions.jsonl');
54
+ }
55
+ /** The composite order id `<workflow>/<run>` — the one place it is built. */
56
+ export function orderId(workflow, run) {
57
+ return `${workflow}/${run}`;
58
+ }
59
+ function defaultWarn(line) {
60
+ process.stderr.write(`${line}\n`);
61
+ }
62
+ /** Identity of a step attempt slot. `attempt` is intentionally not in the key.
63
+ * JSON-encoded rather than joined on a separator character so no combination of
64
+ * workflow/run/step values can collide into one key. */
65
+ function keyOf(workflow, run, step) {
66
+ return JSON.stringify([workflow, run, step]);
67
+ }
68
+ function isNonEmptyString(v) {
69
+ return typeof v === 'string' && v !== '';
70
+ }
71
+ /**
72
+ * Validate one parsed line. Checks exactly the fields whose absence would make
73
+ * the record unusable for a resume: the three key fields plus the harness and
74
+ * token it exists to carry, and a `status` inside the four literals. Everything
75
+ * else is carried verbatim.
76
+ */
77
+ function isSessionRecord(v) {
78
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
79
+ return false;
80
+ const r = v;
81
+ if (!isNonEmptyString(r['workflow']))
82
+ return false;
83
+ if (!isNonEmptyString(r['run']))
84
+ return false;
85
+ if (!isNonEmptyString(r['step']))
86
+ return false;
87
+ if (!isNonEmptyString(r['harness']))
88
+ return false;
89
+ if (!isNonEmptyString(r['token']))
90
+ return false;
91
+ if (typeof r['status'] !== 'string' || !STATUSES.has(r['status']))
92
+ return false;
93
+ return true;
94
+ }
95
+ /** Atomic write: temp file + rename into place. Fs errors propagate to the
96
+ * caller (the one caller, `compact`, is the one that swallows them). Mirrors
97
+ * the private helper in `src/bundle/cache.ts` — copied on purpose rather than
98
+ * exported from there, so the cache module's surface stays about bundles. */
99
+ function atomicWrite(filePath, content) {
100
+ const dir = join(filePath, '..');
101
+ mkdirSync(dir, { recursive: true });
102
+ const tmp = join(dir, `.${Math.random().toString(36).slice(2)}-${process.pid}-${Date.now()}.tmp`);
103
+ writeFileSync(tmp, content);
104
+ try {
105
+ renameSync(tmp, filePath);
106
+ }
107
+ catch (err) {
108
+ try {
109
+ unlinkSync(tmp);
110
+ }
111
+ catch {
112
+ // best-effort cleanup
113
+ }
114
+ throw err;
115
+ }
116
+ }
117
+ /**
118
+ * Every valid record in `file`, oldest first. A missing/unreadable file reads as
119
+ * `[]`. Blank lines are skipped silently; every other unusable line is skipped
120
+ * and reported through `warn` with its 1-indexed line number. Never throws.
121
+ */
122
+ export function readSessions(file, opts = {}) {
123
+ const warn = opts.warn ?? defaultWarn;
124
+ let raw;
125
+ try {
126
+ raw = readFileSync(file, 'utf8');
127
+ }
128
+ catch {
129
+ return []; // fail-open: no store yet is the normal first-run case
130
+ }
131
+ const out = [];
132
+ const lines = raw.split('\n');
133
+ for (let i = 0; i < lines.length; i++) {
134
+ const line = lines[i];
135
+ if (line === undefined)
136
+ continue; // noUncheckedIndexedAccess
137
+ if (line.trim() === '')
138
+ continue; // blank lines are not corruption
139
+ let parsed;
140
+ try {
141
+ parsed = JSON.parse(line);
142
+ }
143
+ catch {
144
+ warn(`owenloop work sessions: skipping corrupt record at ${file}:${i + 1}`);
145
+ continue;
146
+ }
147
+ if (!isSessionRecord(parsed)) {
148
+ warn(`owenloop work sessions: skipping corrupt record at ${file}:${i + 1}`);
149
+ continue;
150
+ }
151
+ out.push(parsed);
152
+ }
153
+ return out;
154
+ }
155
+ /**
156
+ * The newest record for `(workflow, run, step)`, or `null` when the file is
157
+ * missing or holds no match. Scans forward and keeps the LAST match (last-wins).
158
+ * Side-effect-free — it never writes, never compacts, and never throws.
159
+ */
160
+ export function latestFor(file, workflow, run, step) {
161
+ const want = keyOf(workflow, run, step);
162
+ let best = null;
163
+ for (const rec of readSessions(file)) {
164
+ if (keyOf(rec.workflow, rec.run, rec.step) === want)
165
+ best = rec;
166
+ }
167
+ return best;
168
+ }
169
+ /**
170
+ * Rewrite `file` with only the last record per `(workflow, run, step)`,
171
+ * preserving FIRST-SEEN key order, via temp file + rename. Corrupt lines are
172
+ * dropped in the process (they were already unreadable). A missing file is a
173
+ * no-op. Fs failures propagate here; `appendSession` is what swallows them.
174
+ */
175
+ export function compact(file, opts = {}) {
176
+ const records = readSessions(file, opts);
177
+ if (records.length === 0)
178
+ return;
179
+ const byKey = new Map();
180
+ for (const rec of records) {
181
+ // Map preserves first-insertion order across re-set, which is exactly the
182
+ // first-seen key order we want to keep.
183
+ byKey.set(keyOf(rec.workflow, rec.run, rec.step), rec);
184
+ }
185
+ const body = [...byKey.values()].map((r) => JSON.stringify(r)).join('\n');
186
+ atomicWrite(file, `${body}\n`);
187
+ }
188
+ /**
189
+ * PHASE 4 — retire every session of one RUN by appending a `dead` row per step.
190
+ *
191
+ * THE INVARIANT IT ENFORCES: session lifetime equals cwd lifetime. When the
192
+ * per-run work directory is removed, the work those sessions were revising is
193
+ * gone, so resuming into a freshly recreated (and empty) directory at the same
194
+ * path would hand the agent a conversation about files that no longer exist. The
195
+ * `prev.status !== 'dead'` precondition in `src/agent/loop.ts` is what refuses
196
+ * the resume; this function is what makes the status say `dead`.
197
+ *
198
+ * WHY A NEW ROW RATHER THAN A REWRITE: the store is append-only and last-wins per
199
+ * `(workflow, run, step)`, so appending a copy with `status: 'dead'` shadows the
200
+ * live row without rewriting history — and it keeps the ACCEPTED RACE in this
201
+ * module's header (compaction losing concurrent appends) as the only writer race.
202
+ *
203
+ * IDEMPOTENT: a key whose newest row is already `dead` is skipped, so a sweep
204
+ * that reaps the same run twice appends nothing the second time.
205
+ *
206
+ * SCOPE: the newest row per `(workflow, run, step)` for the given run, across
207
+ * EVERY step of that run — the work directory is per-run, so every step's session
208
+ * lived in it.
209
+ *
210
+ * FAILURE STANCE: `appendSession` PROPAGATES (see the header), and so does this.
211
+ * The caller — the work-directory reaper — must be able to see the failure,
212
+ * because retiring the sessions is a precondition of removing the directory, not
213
+ * a side note.
214
+ *
215
+ * Returns the step names actually marked, so a sweep can log a count.
216
+ */
217
+ export function markRunSessionsDead(file, workflow, run, now, opts = {}) {
218
+ const newest = new Map();
219
+ for (const rec of readSessions(file, opts)) {
220
+ if (rec.workflow !== workflow || rec.run !== run)
221
+ continue;
222
+ newest.set(keyOf(rec.workflow, rec.run, rec.step), rec);
223
+ }
224
+ const marked = [];
225
+ for (const rec of newest.values()) {
226
+ if (rec.status === 'dead')
227
+ continue; // already retired — nothing to append
228
+ appendSession(file, { ...rec, status: 'dead', updatedAt: now }, opts);
229
+ marked.push(rec.step);
230
+ }
231
+ return marked;
232
+ }
233
+ /**
234
+ * PHASE 6, ITEM 4 — retire the `active` sessions of runs that are no longer
235
+ * running, so a crash or a reboot does not leave the store claiming a turn is in
236
+ * flight when no process exists.
237
+ *
238
+ * WHAT IS BROKEN WITHOUT THIS. `src/agent/loop.ts` writes `status: 'active'` when
239
+ * a turn starts and rewrites it at turn end. A worker killed mid-turn — SIGKILL,
240
+ * a panic, a reboot — never reaches the rewrite, so the newest row for that step
241
+ * says `active` forever. Nothing else ever corrects it.
242
+ *
243
+ * ── WHY THIS IS NOT `markRunSessionsDead` ────────────────────────────────────
244
+ *
245
+ * `markRunSessionsDead` retires EVERY non-`dead` newest row of a run. Reusing it
246
+ * here would destroy exactly the capability this phase has to keep working:
247
+ * `src/agent/loop.ts` refuses to resume a session whose previous status is
248
+ * `dead`, and a `turn-ended` or `submitted` row is a COMPLETED turn whose
249
+ * provider-side session is intact. A reboot does not invalidate one. Leaving
250
+ * those rows alone is precisely what "resume still works after a reboot" means.
251
+ *
252
+ * So ONLY `active` rows are eligible, and only for runs absent from
253
+ * `liveRunIds`.
254
+ *
255
+ * ── WHY RETIRING AN ORPHANED `active` ROW IS THE RIGHT DIRECTION TO BE WRONG ──
256
+ *
257
+ * An interrupted turn is the state you least want to resume into: the harness may
258
+ * have half-applied tool calls the worker has no record of, so a resumed session
259
+ * would carry a model that believes work happened which did not. The cost of
260
+ * retiring it is one cold replay. The cost of resuming it is silent divergence.
261
+ *
262
+ * ── KNOWN FALSE POSITIVE, STATED RATHER THAN ENGINEERED AROUND ───────────────
263
+ *
264
+ * An `owenloop work agent-run` started BY HAND, outside the shift, has no child record
265
+ * in the shift state dir, so a shift booting at that moment sees its `active` row
266
+ * as orphaned and retires it. The cost is one cold replay on a hand-run debugging
267
+ * session. Two things keep it small: the caller invokes this at BOOT only, which
268
+ * narrows the window to an instant, and every retirement is returned so the
269
+ * caller can log it with its `(workflow, run, step)`. Do NOT add a pid field to
270
+ * `SessionRecord` to close this — the record is deliberately machine-portable
271
+ * metadata, and the shift state dir is already the system of record for liveness.
272
+ *
273
+ * IDEMPOTENT: the rows it appends are `dead`, so a second call finds nothing
274
+ * `active` left and appends nothing.
275
+ *
276
+ * FAILURE STANCE: `appendSession` propagates, and so does this — same as
277
+ * `markRunSessionsDead`.
278
+ *
279
+ * @param liveRunIds run ids with a live `agent-run` child RIGHT NOW. A run in
280
+ * this set is skipped whatever its status.
281
+ * @returns the records that were retired, as they were BEFORE retirement, so the
282
+ * caller can log what it took away.
283
+ */
284
+ export function reconcileActiveSessions(file, liveRunIds, now, opts = {}) {
285
+ const newest = new Map();
286
+ for (const rec of readSessions(file, opts)) {
287
+ newest.set(keyOf(rec.workflow, rec.run, rec.step), rec);
288
+ }
289
+ const retired = [];
290
+ for (const rec of newest.values()) {
291
+ if (rec.status !== 'active')
292
+ continue; // a completed turn is still resumable
293
+ if (liveRunIds.has(rec.run))
294
+ continue; // its worker is alive; the row is true
295
+ appendSession(file, { ...rec, status: 'dead', updatedAt: now }, opts);
296
+ retired.push(rec);
297
+ }
298
+ return retired;
299
+ }
300
+ /**
301
+ * Append one record, then compact when the file has grown past `maxBytes`.
302
+ *
303
+ * The whole line is written in ONE `appendFileSync` call (with its trailing
304
+ * newline) so concurrent workers' O_APPEND writes interleave line-atomically on
305
+ * local filesystems. Append failures PROPAGATE — see this module's failure
306
+ * stance. The post-append compaction is best-effort and swallowed.
307
+ */
308
+ export function appendSession(file, rec, opts = {}) {
309
+ mkdirSync(join(file, '..'), { recursive: true });
310
+ appendFileSync(file, `${JSON.stringify(rec)}\n`);
311
+ const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
312
+ try {
313
+ if (statSync(file).size > maxBytes)
314
+ compact(file, opts);
315
+ }
316
+ catch {
317
+ // best-effort: an un-compacted (or unstatable) file is still correct.
318
+ }
319
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Neutral harness-side types that are NOT part of the runtime session contract.
3
+ *
4
+ * `contract.ts` holds the things a running session needs (`StartArgs`,
5
+ * `AgentEvent`, `HarnessSessionRef`, `StepPermissions`). This file holds the
6
+ * things a harness declares ABOUT step definitions — today just `LintFinding`,
7
+ * the shape `owenloop work lint` prints.
8
+ *
9
+ * ISOLATION RULE applies here exactly as it does to every other file under
10
+ * `src/harness/`: no vendor name in this file, comments included. The adapter
11
+ * modules are the only allowlisted exceptions, and the allowlist lives in
12
+ * `test/harness-isolation.test.ts`, not here.
13
+ */
14
+ /**
15
+ * One finding from linting a single step's harness option bag (`x.harness`).
16
+ *
17
+ * `field` is the bag key the finding anchors to (`model`, `maxTurns`, …) and is
18
+ * absent when the finding is about the bag as a whole. The caller renders the
19
+ * location — `src/roles/lint.ts` prints `x.harness.<field>` — so a finding
20
+ * carries the field NAME and never a rendered path.
21
+ */
22
+ export interface LintFinding {
23
+ severity: 'error' | 'warning';
24
+ /** The step the finding is about. */
25
+ step: string;
26
+ /** The bag field it anchors to, when applicable (e.g. `model`, `maxTurns`). */
27
+ field?: string;
28
+ message: string;
29
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Neutral harness-side types that are NOT part of the runtime session contract.
3
+ *
4
+ * `contract.ts` holds the things a running session needs (`StartArgs`,
5
+ * `AgentEvent`, `HarnessSessionRef`, `StepPermissions`). This file holds the
6
+ * things a harness declares ABOUT step definitions — today just `LintFinding`,
7
+ * the shape `owenloop work lint` prints.
8
+ *
9
+ * ISOLATION RULE applies here exactly as it does to every other file under
10
+ * `src/harness/`: no vendor name in this file, comments included. The adapter
11
+ * modules are the only allowlisted exceptions, and the allowlist lives in
12
+ * `test/harness-isolation.test.ts`, not here.
13
+ */
14
+ export {};
@@ -0,0 +1,38 @@
1
+ /**
2
+ * THE composition root for the harness registry — the one file in `src/` that
3
+ * names the adapter modules, and the only file that decides which adapter is the
4
+ * default.
5
+ *
6
+ * WHY THIS FILE EXISTS. `src/harness/registry.ts` starts empty and deliberately
7
+ * forbids a barrel, so somebody has to import each adapter module for its
8
+ * `register(...)` side effect to fire. Through Phase 5 that somebody was TWO
9
+ * files — `src/roles/agent-run.ts` and `src/roles/lint.ts` — each carrying the
10
+ * same import pair, kept in the same order BY HAND. Phase 6 collapsed them into
11
+ * this module for two reasons:
12
+ *
13
+ * 1. ORDER IS LOAD-BEARING AND MUST HAVE ONE OWNER. `defaultHarnessId()`
14
+ * returns `registeredHarnessIds()[0]`, i.e. whichever adapter registered
15
+ * first. Two roots meant two places that had to agree, and a reorder in one
16
+ * of them would silently change which harness runs a step that names none.
17
+ * One file, one order, and `test/vendor-gate.test.ts` asserts the resulting
18
+ * default explicitly so an accidental reorder fails a test.
19
+ * 2. IT KEEPS THE VENDOR-NAMING SURFACE SMALL. `test/vendor-gate.test.ts`
20
+ * allowlists the files under `src/`/`bin/` that may name a harness vendor.
21
+ * Consolidating drops that allowlist from five entries to four.
22
+ *
23
+ * SAFE BY ESM SEMANTICS: module evaluation is cached, so each adapter's
24
+ * `register(...)` fires exactly once no matter how many modules import this one.
25
+ *
26
+ * IMPORT ORDER — DO NOT SORT THIS BLOCK. The FIRST id registered is the default
27
+ * harness. `claude.ts` is first and `claude-code` is therefore the default; that
28
+ * matches the pre-consolidation order in `src/roles/agent-run.ts` and is pinned
29
+ * by a test.
30
+ *
31
+ * Importers: `src/roles/agent-run.ts` (the worker), `src/roles/lint.ts` (lint
32
+ * judges a harness-less step by the SAME default that will run it), and
33
+ * `src/roles/sessions.ts` (it maps a recorded harness id to that adapter's
34
+ * resume command). A new caller of `adapterFor` / `defaultHarnessId` imports
35
+ * THIS module — it does not add adapter imports of its own.
36
+ */
37
+ import './harness/claude.ts';
38
+ import './harness/codex.ts';
@@ -0,0 +1,38 @@
1
+ /**
2
+ * THE composition root for the harness registry — the one file in `src/` that
3
+ * names the adapter modules, and the only file that decides which adapter is the
4
+ * default.
5
+ *
6
+ * WHY THIS FILE EXISTS. `src/harness/registry.ts` starts empty and deliberately
7
+ * forbids a barrel, so somebody has to import each adapter module for its
8
+ * `register(...)` side effect to fire. Through Phase 5 that somebody was TWO
9
+ * files — `src/roles/agent-run.ts` and `src/roles/lint.ts` — each carrying the
10
+ * same import pair, kept in the same order BY HAND. Phase 6 collapsed them into
11
+ * this module for two reasons:
12
+ *
13
+ * 1. ORDER IS LOAD-BEARING AND MUST HAVE ONE OWNER. `defaultHarnessId()`
14
+ * returns `registeredHarnessIds()[0]`, i.e. whichever adapter registered
15
+ * first. Two roots meant two places that had to agree, and a reorder in one
16
+ * of them would silently change which harness runs a step that names none.
17
+ * One file, one order, and `test/vendor-gate.test.ts` asserts the resulting
18
+ * default explicitly so an accidental reorder fails a test.
19
+ * 2. IT KEEPS THE VENDOR-NAMING SURFACE SMALL. `test/vendor-gate.test.ts`
20
+ * allowlists the files under `src/`/`bin/` that may name a harness vendor.
21
+ * Consolidating drops that allowlist from five entries to four.
22
+ *
23
+ * SAFE BY ESM SEMANTICS: module evaluation is cached, so each adapter's
24
+ * `register(...)` fires exactly once no matter how many modules import this one.
25
+ *
26
+ * IMPORT ORDER — DO NOT SORT THIS BLOCK. The FIRST id registered is the default
27
+ * harness. `claude.ts` is first and `claude-code` is therefore the default; that
28
+ * matches the pre-consolidation order in `src/roles/agent-run.ts` and is pinned
29
+ * by a test.
30
+ *
31
+ * Importers: `src/roles/agent-run.ts` (the worker), `src/roles/lint.ts` (lint
32
+ * judges a harness-less step by the SAME default that will run it), and
33
+ * `src/roles/sessions.ts` (it maps a recorded harness id to that adapter's
34
+ * resume command). A new caller of `adapterFor` / `defaultHarnessId` imports
35
+ * THIS module — it does not add adapter imports of its own.
36
+ */
37
+ import "./harness/claude.js";
38
+ import "./harness/codex.js";
@@ -0,0 +1,36 @@
1
+ /**
2
+ * The `hold` loop (C4) — keeps one order's lease alive on behalf of an
3
+ * interactive session, and performs the final-breath handoff on shutdown.
4
+ *
5
+ * The cadence/backoff/clock-jump/final-breath CORE moved to `src/lease/loop.ts`
6
+ * in C5 (plan decision 4) so `hold` and the self-leasing `exec` share ONE
7
+ * implementation. This module is now a thin adapter: it fixes the role prefix to
8
+ * `'hold'` (so every emitted message string is byte-identical to C4) and
9
+ * re-exports the loop's public surface under the hold names its callers and
10
+ * tests already import. `hold` never reads the order packet, so it omits
11
+ * `onOrder`; its `stop(reason?)` always releases (the session died — hand the
12
+ * order back).
13
+ *
14
+ * See `src/lease/loop.ts` for the full lifecycle documentation.
15
+ */
16
+ import { type LeaseLoopOptions, type LeaseOutcome, type StopOptions } from '../lease/loop.ts';
17
+ /** The hold run's outcome — the lease outcome under the hold name. */
18
+ export type HoldOutcome = LeaseOutcome;
19
+ /**
20
+ * hold's options are the lease options minus the one internal it fixes (`role`).
21
+ * `onOrder` stays available: the CLI `hold` never wires it (it doesn't read the
22
+ * packet), but the D2 `hold --mcp` mount does — its `get_order` tool returns the
23
+ * order packet the loop's first contact already fetched.
24
+ */
25
+ export type HoldLoopOptions = Omit<LeaseLoopOptions, 'role'>;
26
+ export interface HoldLoop {
27
+ run(): Promise<HoldOutcome>;
28
+ /**
29
+ * Stop the loop. `stopOpts.release:false` skips the final-breath release — the
30
+ * `hold --mcp` submit tool passes it once a submit CLOSES the run (the claim is
31
+ * already gone, so releasing would be a confusing no-op). The CLI hold's signal
32
+ * path passes no opts, so it still releases (the session died — hand it back).
33
+ */
34
+ stop(reason?: string, stopOpts?: StopOptions): void;
35
+ }
36
+ export declare function createHoldLoop(opts: HoldLoopOptions): HoldLoop;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The `hold` loop (C4) — keeps one order's lease alive on behalf of an
3
+ * interactive session, and performs the final-breath handoff on shutdown.
4
+ *
5
+ * The cadence/backoff/clock-jump/final-breath CORE moved to `src/lease/loop.ts`
6
+ * in C5 (plan decision 4) so `hold` and the self-leasing `exec` share ONE
7
+ * implementation. This module is now a thin adapter: it fixes the role prefix to
8
+ * `'hold'` (so every emitted message string is byte-identical to C4) and
9
+ * re-exports the loop's public surface under the hold names its callers and
10
+ * tests already import. `hold` never reads the order packet, so it omits
11
+ * `onOrder`; its `stop(reason?)` always releases (the session died — hand the
12
+ * order back).
13
+ *
14
+ * See `src/lease/loop.ts` for the full lifecycle documentation.
15
+ */
16
+ import { createLeaseLoop } from "../lease/loop.js";
17
+ export function createHoldLoop(opts) {
18
+ const loop = createLeaseLoop({ ...opts, role: 'hold' });
19
+ return {
20
+ run: () => loop.run(),
21
+ stop: (reason, stopOpts) => loop.stop(reason, stopOpts),
22
+ };
23
+ }