@stravica-ai/digital-operator-pa 0.1.21 → 0.1.23

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.
@@ -128,11 +128,74 @@ id/tag is estate-side work, not part of this package.
128
128
  proceeds to push. The audit record adds
129
129
  `autoResolved: <N>` + `autoResolvedPaths: [...]` to the `ok` line.
130
130
 
131
- If **any** conflicted path is outside the allowlist,
132
- `git rebase --abort` runs and sync exits 2 with status `fail-rebase`
133
- as before. Real content conflicts still surface for human resolution;
134
- the audit record includes `conflictedPaths: [...]` for the disallowed
135
- paths so the on-call has a starting point.
131
+ If **any** conflicted path is outside the allowlist, the tool
132
+ attempts **self-heal on rebase-abort** (R2, w-2026-08-12-004, replaces
133
+ the pre-R2 "abort and wedge" behaviour): estate-sync's own version of
134
+ each conflicting path is queued to
135
+ `<repoRoot>/.cache/estate-sync/pending/<pathSlug>__<firstSeenTs>` with
136
+ a JSON sidecar carrying `originalPath`, `conflictingUpstreamCommitSha`,
137
+ `upstreamBlobShaAtQueue`, `attemptCount`, `firstSeen`, and
138
+ `alertLevel`. The pending content is fsynced BEFORE any git mutation
139
+ runs, so a queue failure never triggers a reset. Then four cascading
140
+ guards fire (HEAD sha equals the sha recorded immediately after
141
+ `git commit`; HEAD^ exists; exactly one commit in `HEAD^..HEAD`;
142
+ exactly one commit ahead of `origin/<branch>`); on any guard failure
143
+ the tool falls through to the classic `fail-rebase` behaviour and
144
+ stays wedged loudly. When all guards pass, `git reset --soft HEAD^`
145
+ drops estate-sync's own commit while leaving BOTH the index and the
146
+ working tree untouched — every non-conflicting path in the dropped
147
+ commit stays staged and its bytes stay on disk for the next tick to
148
+ recommit. Then surgically per conflicting path: newly-added paths get
149
+ `git rm --cached -- <path>` + `fs.unlink` (unstaged and removed from
150
+ disk; their bytes live in pending); modified paths get
151
+ `git checkout HEAD -- <path>` (restored to the parent's version in
152
+ both index and working tree). The audit record uses one of
153
+ `fail-rebase-queued` (alertLevel `warn`, attempts < 5),
154
+ `fail-rebase-stuck` (alertLevel `error`, attempts >= 5), or
155
+ `fail-rebase-needs-human` (divergence detected during drain) with
156
+ exit code **0** — the process exits healthy because the workspace
157
+ itself is fast-forwardable again, while the `fail-*` status routes
158
+ through librarian-alerts (when wired to estate-sync's runs.jsonl).
159
+
160
+ > **Why `--soft` and not `--keep`** (correction landed 2026-08-12 via
161
+ > the PR-120 fresh-context review): `--keep <ref>` updates the
162
+ > working tree to match `<ref>` on every file that differs between
163
+ > HEAD and `<ref>`. In a multi-file estate-sync commit (which is the
164
+ > design — step 6 scoops every in-scope dirty path), that means
165
+ > every non-conflicting path in the dropped commit would be silently
166
+ > destroyed (newly-added files deleted, modifications reverted).
167
+ > `--soft` leaves the index and working tree entirely alone; the
168
+ > surgical scope above touches only the conflicting paths, so
169
+ > non-conflicting content survives across the drop.
170
+
171
+ On every subsequent tick, **DRAIN** runs at the top (inside the PID
172
+ lock, after fetch so `origin/<branch>` refs are fresh), oldest-first.
173
+ For each pending entry the tool compares the sidecar's
174
+ `upstreamBlobShaAtQueue` against origin's blob NOW and picks one of
175
+ three actions:
176
+ - **`already-delivered`** — upstream's current blob bytes exactly
177
+ match the pending content (another writer pushed our version for
178
+ us). Pending removed cleanly, no workspace write.
179
+ - **`staged-for-retry`** — upstream blob is unchanged since queue
180
+ time. Copy the pending bytes back into the workspace at
181
+ `originalPath`; step 6 will stage them and step 7 will rebase
182
+ normally. Pending removed ONLY after commit + push are confirmed
183
+ on HEAD (`finaliseDrainOnPushSuccess`); a crash between drain
184
+ and commit leaves the pending file intact so the next tick
185
+ re-evaluates.
186
+ - **`divergence-held`** — upstream now has a DIFFERENT resolution
187
+ than the sidecar recorded at queue time (a third writer intervened,
188
+ a human reconciled with different bytes, etc.). The sidecar is
189
+ stamped `alertLevel: 'needs-human'` (sticky — never de-escalates
190
+ back to warn or error), and the workspace is NOT touched. This
191
+ blocks the silent-clobber hazard the earlier ratified drain
192
+ sketch had, where re-applying stale bytes would overwrite the
193
+ winner's resolution.
194
+
195
+ Pending queue lives at `.cache/estate-sync/pending/`, gitignored per
196
+ the tooling standard §16. Content-safety invariant: no reset ever
197
+ runs when the queue write fails, and no workspace write ever happens
198
+ when upstream has diverged.
136
199
 
137
200
  ### Registry-scoped commit set
138
201
 
@@ -229,7 +292,13 @@ One JSON object per line, camelCase keys (§11 of the tooling standard):
229
292
  | `branch` | string | The current branch name. Present on `ok` and `noop-nothing-to-do`. |
230
293
  | `autoResolved` | number | Number of allowlisted regenerated-artifact paths auto-resolved during a rebase conflict. `ok` only, present iff > 0. |
231
294
  | `autoResolvedPaths` | string[] | The specific paths that got the `--ours` treatment. `ok` only, paired with `autoResolved`. |
232
- | `conflictedPaths` | string[] | The disallowed conflicted paths that forced the abort. `fail-rebase` only, when at least one conflict was outside the allowlist. |
295
+ | `conflictedPaths` | string[] | The disallowed conflicted paths. Present on `fail-rebase` (self-heal declined, wedged loud), and on any `fail-rebase-queued` / `fail-rebase-stuck` / `fail-rebase-needs-human` (self-heal ran, workspace healthy again). |
296
+ | `selfHealed` | bool | Set to `true` on any self-heal audit record (`fail-rebase-queued`, `-stuck`, or `-needs-human`). |
297
+ | `droppedCommit` | string | 40-hex sha of estate-sync's own commit that self-heal dropped. Present on all self-heal records. |
298
+ | `queued` | object[] | Summary of each queued pending entry (id, originalPath, attemptCount, alertLevel, upstreamBlobShaAtQueue, conflictingUpstreamCommitSha, pendingPath). Present on all self-heal records. |
299
+ | `drained` | object[] | Summary of drain results for this tick (id, originalPath, action, attemptCount, optional alertLevel + upstream blob shas). Present on any tick that saw pending entries at start-of-tick. |
300
+ | `drainFinalised` | string[] | Ids of pending entries removed after commit + push were confirmed on HEAD. Present on `ok` records that carried `drained` entries with action `staged-for-retry`. |
301
+ | `selfHealDeclined` | object | `{ stage, reason }` when self-heal was invoked but refused (queue-write failure, guard failure, reset failure). Paired with `status: fail-rebase` and `exitCode: 2`. |
233
302
 
234
303
  Status vocabulary (closed set):
235
304
 
@@ -238,13 +307,25 @@ Status vocabulary (closed set):
238
307
  | `ok` | 0 | Commit + push (or pull-only) succeeded. |
239
308
  | `noop-nothing-to-do` | 0 | Clean tree, no local commits ahead, up-to-date with origin. |
240
309
  | `noop-locked` | 0 | Another sync run holds the lock. |
241
- | `fail-rebase` | 2 | `git pull --rebase` conflicted; rebase aborted. Human reconciliation required. |
310
+ | `fail-rebase` | 2 | `git pull --rebase` conflicted; self-heal either not attempted (regenerated-artifacts branch already resolved) or declined (guard-failure / queue-write-failure / reset-failure). Workspace is wedged, human reconciliation required. |
311
+ | `fail-rebase-queued` | 0 | Self-heal ran on a non-allowlist conflict, dropped estate-sync's own commit under guard, queued the conflicting content for retry. Workspace is fast-forwardable again; librarian-alerts should surface the queued path (`alertLevel: warn`, `attemptCount < 5`). |
312
+ | `fail-rebase-stuck` | 0 | Same as `fail-rebase-queued` but the pending entry's `attemptCount >= 5` — escalated alert (`alertLevel: error`). |
313
+ | `fail-rebase-needs-human` | 0 | Self-heal ran, drain-time upstream divergence detected on a pending entry — someone else pushed a different resolution while ours was queued. Workspace NOT touched; pending held indefinitely (`alertLevel: needs-human`, sticky). |
242
314
  | `fail-push` | 2 | Push rejected even after one rebase-and-retry. Commit is local-only. |
243
315
  | `fail-git` | 3 | A `git status`/`add`/`commit` command itself errored (transport or IO). |
244
316
  | `fail-cli-bootstrap` | varies | parseArgs / import / startup failure before runSync was reached. |
245
317
 
246
- Consumer contract: monitors should treat `status == 'ok'` and any
247
- `noop-*` as healthy; any `fail-*` as failing.
318
+ Consumer contract:
319
+ - **Process health** — check `exitCode`. `0` = the sync process itself is
320
+ healthy (nothing to fix at cron / systemd level). This is the correct
321
+ signal for "is the cron process wedged?"
322
+ - **Alert routing** — check `status.startsWith('fail-')`. Every `fail-*`
323
+ status is a human-visible alert regardless of exitCode, because
324
+ self-heal statuses (`fail-rebase-queued`, `fail-rebase-stuck`,
325
+ `fail-rebase-needs-human`) intentionally exit 0 (workspace is healthy,
326
+ process is healthy) while surfacing that a pending entry needs
327
+ attention. Escalation ladder inside self-heal: `queued` → `stuck` at
328
+ attempt >= 5 → `needs-human` on drain-time divergence (sticky).
248
329
 
249
330
  ## Exit codes
250
331
 
@@ -24,6 +24,24 @@ export async function writeJson(path, value) {
24
24
  await writeFile(path, body, 'utf8');
25
25
  }
26
26
 
27
+ /**
28
+ * Write a JSON file with O_CREAT|O_EXCL semantics. Refuses to overwrite
29
+ * an existing file (throws a Node error with `code === 'EEXIST'`).
30
+ *
31
+ * Same shape rules as `writeJson`: 2-space indent, trailing newline,
32
+ * parent directories created on demand. Callers that follow an
33
+ * allocate-then-write pattern use this to turn a same-author write race
34
+ * into an EEXIST they can retry at NNN+1, rather than the plain flag
35
+ * `'w'` behaviour where the second write silently clobbered the first.
36
+ * Same primitive `escalate.mjs` in `librarian-pr-intake` uses for the
37
+ * librarian's own allocator — the two writers now share one race model.
38
+ */
39
+ export async function writeJsonExclusive(path, value) {
40
+ await mkdir(dirname(path), { recursive: true });
41
+ const body = JSON.stringify(value, null, 2) + '\n';
42
+ await writeFile(path, body, { encoding: 'utf8', flag: 'wx' });
43
+ }
44
+
27
45
  /**
28
46
  * Ensure a directory exists. Returns the absolute path.
29
47
  */
@@ -26,7 +26,22 @@ import {
26
26
  } from '../../../engineering-pa-core/src/workItemId/index.mjs';
27
27
 
28
28
  import { getRepoRoot } from './repo-root.mjs';
29
- import { readJson, writeJson, ensureDir, listJsonFiles, today } from './io.mjs';
29
+ import {
30
+ readJson,
31
+ writeJson,
32
+ writeJsonExclusive,
33
+ ensureDir,
34
+ listJsonFiles,
35
+ today,
36
+ } from './io.mjs';
37
+
38
+ // Upper bound on the O_CREAT|O_EXCL retry loop in `createWork`. Same
39
+ // value the librarian-pr-intake allocator uses (`escalate.mjs`); both
40
+ // close the same class of same-author race between allocator scan and
41
+ // exclusive write. 99 is comfortably above any realistic burst — 999 is
42
+ // the per-author-per-day NNN ceiling so a runaway loop still terminates
43
+ // well below it.
44
+ const MAX_ALLOCATE_RETRIES = 99;
30
45
 
31
46
  const STATUSES = new Set(['draft', 'planned', 'in-progress', 'blocked', 'done', 'archived']);
32
47
 
@@ -63,29 +78,22 @@ function validatePriority(priority) {
63
78
  }
64
79
 
65
80
  /**
66
- * Highest NNN already allocated for `dateStr` in THIS author's per-day
67
- * sequence. Legacy items (`w-YYYY-MM-DD-NNN` with no author segment)
68
- * do not count toward any author's sequence — each writer starts from
69
- * 001 on the day writer-scoping takes effect and existing legacy items
70
- * simply occupy a separate, older space.
81
+ * Highest NNN currently visible on disk for `dateStr` in THIS author's
82
+ * per-day sequence. Legacy items (`w-YYYY-MM-DD-NNN` with no author
83
+ * segment) do not count toward any author's sequence — each writer
84
+ * starts from 001 on the day writer-scoping takes effect and existing
85
+ * legacy items simply occupy a separate, older space.
71
86
  *
72
- * If 999 is already taken, throws — callers should treat as an
73
- * operational failure and report. In practice this is unreachable
74
- * because NNN is per-author-per-day, not shared.
87
+ * The value is a starting point for `createWork`'s allocate-write-retry
88
+ * loop, not a final answer: between the scan and the exclusive write,
89
+ * another same-author `pa work create` may have landed a same-NNN file
90
+ * (same-author write race, structurally possible when two operator
91
+ * sessions run concurrently on shared work/). The O_CREAT|O_EXCL retry
92
+ * in `createWork` is what closes that residual race.
75
93
  */
76
- async function nextWorkNumber(repoRoot, dateStr, author) {
77
- const dir = join(repoRoot, 'work');
78
- const files = await listJsonFiles(dir);
79
- const max = maxNForAuthorOnDate(files, dateStr, author);
80
- const next = max + 1;
81
- if (next > 999) {
82
- const err = new Error(
83
- `no free work-item slot for ${dateStr} in author=${author} sequence (NNN exhausted)`,
84
- );
85
- err.exitCode = 2;
86
- throw err;
87
- }
88
- return next;
94
+ async function scanMaxNInWorkDir(workDir, dateStr, author) {
95
+ const files = await listJsonFiles(workDir);
96
+ return maxNForAuthorOnDate(files, dateStr, author);
89
97
  }
90
98
 
91
99
  /**
@@ -101,6 +109,15 @@ async function nextWorkNumber(repoRoot, dateStr, author) {
101
109
  * with an actionable message naming all three sources — a mint with no
102
110
  * author identity is the exact defect R1 exists to close, so we refuse
103
111
  * to fall back to any hard-coded default.
112
+ *
113
+ * Write is O_CREAT|O_EXCL via `writeJsonExclusive`. If two same-author
114
+ * `createWork` invocations race (same estate, same day, two operator
115
+ * sessions), the allocator scan may hand both callers the same base
116
+ * NNN; the first exclusive write lands and the second gets EEXIST,
117
+ * which the retry loop below resolves by trying NNN+1, NNN+2, ... up
118
+ * to `MAX_ALLOCATE_RETRIES`. Cross-writer collisions (different author
119
+ * tokens) are already structurally impossible after R1
120
+ * (w-2026-08-12-001) — this closes the residual same-author window.
104
121
  */
105
122
  export async function createWork(opts) {
106
123
  if (!opts.title) {
@@ -127,28 +144,48 @@ export async function createWork(opts) {
127
144
  await ensureDir(workDir);
128
145
 
129
146
  const dateStr = today();
130
- const nnn = await nextWorkNumber(repoRoot, dateStr, author);
131
- const id = buildWorkItemId({ date: dateStr, author, nnn });
132
- const path = join(workDir, `${id}.json`);
133
-
134
- const item = {
135
- id,
136
- projectId: opts.projectId || null,
137
- title: opts.title,
138
- category: opts.category || 'chore',
139
- status: 'draft',
140
- priority: opts.priority == null ? 2 : opts.priority,
141
- owner: opts.owner || 'system-architect',
142
- assignee: opts.assignee || opts.owner || 'system-architect',
143
- created: dateStr,
144
- updated: dateStr,
145
- completedAt: null,
146
- summary: opts.summary || '',
147
- blocked: null,
148
- links: [],
149
- };
150
- await writeJson(path, item);
151
- return { id, path };
147
+ const baseN = await scanMaxNInWorkDir(workDir, dateStr, author);
148
+
149
+ for (let offset = 1; offset <= MAX_ALLOCATE_RETRIES; offset += 1) {
150
+ const nnn = baseN + offset;
151
+ if (nnn > 999) {
152
+ const err = new Error(
153
+ `no free work-item slot for ${dateStr} in author=${author} sequence (NNN exhausted)`,
154
+ );
155
+ err.exitCode = 2;
156
+ throw err;
157
+ }
158
+ const id = buildWorkItemId({ date: dateStr, author, nnn });
159
+ const path = join(workDir, `${id}.json`);
160
+ const item = {
161
+ id,
162
+ projectId: opts.projectId || null,
163
+ title: opts.title,
164
+ category: opts.category || 'chore',
165
+ status: 'draft',
166
+ priority: opts.priority == null ? 2 : opts.priority,
167
+ owner: opts.owner || 'system-architect',
168
+ assignee: opts.assignee || opts.owner || 'system-architect',
169
+ created: dateStr,
170
+ updated: dateStr,
171
+ completedAt: null,
172
+ summary: opts.summary || '',
173
+ blocked: null,
174
+ links: [],
175
+ };
176
+ try {
177
+ await writeJsonExclusive(path, item);
178
+ return { id, path };
179
+ } catch (e) {
180
+ if (e && e.code === 'EEXIST') continue;
181
+ throw e;
182
+ }
183
+ }
184
+ const err = new Error(
185
+ `pa work create: gave up after ${MAX_ALLOCATE_RETRIES} EEXIST retries from base NNN ${baseN + 1} in ${dateStr} author=${author}`,
186
+ );
187
+ err.exitCode = 2;
188
+ throw err;
152
189
  }
153
190
 
154
191
  /**
@@ -198,3 +198,91 @@ export async function rebaseContinue(runner, { cwd }) {
198
198
  { cwd, env: { ...process.env, GIT_EDITOR: 'true' } },
199
199
  );
200
200
  }
201
+
202
+ // Resolve a ref (default HEAD) to its full sha. Returns { code, sha, stderr }.
203
+ // The self-heal path uses this both to record the sha of estate-sync's own
204
+ // commit at commit time AND to verify HEAD is still that sha immediately
205
+ // before dropping it — the guard that stops the reset ever touching a
206
+ // commit we did not just make.
207
+ export async function revParseSha(runner, { cwd, ref = 'HEAD' } = {}) {
208
+ const r = await runner.spawn('git', ['rev-parse', '--verify', `${ref}^{commit}`], { cwd });
209
+ return { code: r.code, sha: r.stdout.trim(), stderr: r.stderr };
210
+ }
211
+
212
+ // Count commits in a range (e.g. HEAD^..HEAD). Returns { code, count, stderr }.
213
+ // count === 1 is the drop-guard invariant: exactly one commit between HEAD's
214
+ // parent and HEAD (never a merge-commit stack, never zero, never more).
215
+ export async function revListCount(runner, { cwd, range }) {
216
+ const r = await runner.spawn('git', ['rev-list', '--count', range], { cwd });
217
+ const n = Number.parseInt(r.stdout.trim(), 10);
218
+ return { code: r.code, count: Number.isFinite(n) ? n : null, stderr: r.stderr };
219
+ }
220
+
221
+ // git reset --soft <ref>. Moves HEAD to <ref>, leaves BOTH the index and
222
+ // the working tree untouched. This is the load-bearing primitive for the
223
+ // R2 self-heal path: after dropping our commit, the non-conflicting
224
+ // portion of that commit's diff MUST remain staged in the index so the
225
+ // next tick recommits it. --mixed would unstage (still fine for our
226
+ // purposes but noisier), --hard would obliterate everything, and --keep
227
+ // (which we originally used, corrected 2026-08-12 per the reviewer's
228
+ // blocker on PR #120) actively UPDATES the working tree to match <ref>
229
+ // on every file that differs between HEAD and <ref> — meaning every
230
+ // non-conflicting path in the dropped commit gets silently destroyed.
231
+ // --soft leaves the surgical work to the caller: keep what we want,
232
+ // remove or restore only the conflicting paths we've already queued.
233
+ export async function resetSoft(runner, { cwd, ref }) {
234
+ return runner.spawn('git', ['reset', '--soft', ref], { cwd });
235
+ }
236
+
237
+ // git rm --cached -- <path>. Unstages a single path — removes it from the
238
+ // index without touching the working tree. Paired with `fs.unlink` in
239
+ // self-heal to surgically un-stage a newly-added conflicting path after
240
+ // the --soft reset (the addition is queued to pending, so we want the
241
+ // path GONE from the index AND from disk without touching any other
242
+ // staged content).
243
+ export async function rmCached(runner, { cwd, paths }) {
244
+ if (paths.length === 0) return { code: 0, stdout: '', stderr: '' };
245
+ return runner.spawn('git', ['rm', '--cached', '--', ...paths], { cwd });
246
+ }
247
+
248
+ // git hash-object <path>. Computes git's own blob sha for the byte
249
+ // contents of a file, WITHOUT staging or writing anything to the object
250
+ // store. Used by the drain to compare a pending file's bytes against
251
+ // `origin/<branch>:<path>` via matching sha values — binary-safe, no
252
+ // utf8 round-trip, and apples-to-apples (git blob sha both sides).
253
+ export async function hashObject(runner, { cwd, path }) {
254
+ const r = await runner.spawn('git', ['hash-object', '--', path], { cwd });
255
+ return { code: r.code, sha: r.stdout.trim(), stderr: r.stderr };
256
+ }
257
+
258
+ // Does <ref>:<path> exist? `git cat-file -e` exits 0 if yes, non-zero if no.
259
+ // Used by self-heal to decide the working-tree cleanup shape:
260
+ // - path existed at HEAD^ → checkout HEAD^ to restore parent's version
261
+ // - path did NOT exist there → the file was newly added by our commit;
262
+ // remove it from the working tree entirely
263
+ // Getting this branch right is what stops the wedge-loop where our own
264
+ // content, still in the tree after reset, re-conflicts on every tick.
265
+ export async function refPathExists(runner, { cwd, ref, path }) {
266
+ const r = await runner.spawn('git', ['cat-file', '-e', `${ref}:${path}`], { cwd });
267
+ return r.code === 0;
268
+ }
269
+
270
+ // git checkout <ref> -- <paths>. Copies the ref's version of each path into
271
+ // BOTH the index and the working tree. Used by self-heal after the
272
+ // reset --keep HEAD^ to overwrite the (now unstaged) conflicting paths with
273
+ // their pre-commit versions, so the next tick's step 6 doesn't re-stage the
274
+ // content we've deliberately queued out of the way.
275
+ export async function checkoutFromRef(runner, { cwd, ref, paths }) {
276
+ if (paths.length === 0) return { code: 0, stdout: '', stderr: '' };
277
+ return runner.spawn('git', ['checkout', ref, '--', ...paths], { cwd });
278
+ }
279
+
280
+ // Does the ref exist locally? Used to check origin/<branch> before we try
281
+ // to inspect it (a fresh clone with no fetches wouldn't have it). We use
282
+ // `git show-ref --verify --quiet` because it's the ref-existence idiom that
283
+ // doesn't fall back to name-rev heuristics and produces no output on either
284
+ // branch.
285
+ export async function refExists(runner, { cwd, ref }) {
286
+ const r = await runner.spawn('git', ['show-ref', '--verify', '--quiet', ref], { cwd });
287
+ return r.code === 0;
288
+ }