@codeyam-editor/codeyam-editor 0.1.2 → 0.1.3

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.
@@ -76,31 +76,136 @@ function classifyDescribeError(err, stderr) {
76
76
  }
77
77
 
78
78
  // Decide what the startup reap should do for one sidecar. Pure: takes the
79
- // decoded sidecar + GCP-existence verdict + (for adds) container-up verdict,
80
- // returns a tag the caller dispatches on.
81
- // verdict when dispatch
82
- // 'cleanup' destroy gone, OR add gone runDestroyCleanup / runAddCleanup
83
- // 'reconcile-add' add up AND container up ensure roster + recordLaunch, then clear
84
- // 'recover-bootstrap' add instance up but container missing/down re-run cloud:up to finish the half-done bootstrap
85
- // 'clear-only' destroy sidecar but instance still exists just clear the sidecar
86
- // 'leave' gcloud uncertain (exists === null) leave for the next boot
87
- // The (exists, containerUp) split is what distinguishes a finished add from a
88
- // half-provisioned one: a dashboard SIGKILL'd mid-`cloud:up` leaves a GCP
79
+ // decoded sidecar + GCP-existence verdict + (for adds) container-up verdict +
80
+ // (for up adds) project-wiring verdict, returns a tag the caller dispatches on.
81
+ // verdict when dispatch
82
+ // 'cleanup' destroy gone, OR add gone runDestroyCleanup / runAddCleanup
83
+ // 'reconcile-add' add up, container up, project wired (or unknown) ensure roster + recordLaunch, then clear
84
+ // 'half-provisioned' add up, container up, but project NOT wired surface needs-recovery card (finish-wire from cfg)
85
+ // 'recover-bootstrap' add instance up but container missing/down re-run cloud:up to finish the half-done bootstrap
86
+ // 'clear-only' destroy sidecar but instance still exists just clear the sidecar
87
+ // 'leave' gcloud uncertain (exists === null) leave for the next boot
88
+ // The (exists, containerUp) split distinguishes a finished add from a container-
89
+ // down half-provisioned one: a dashboard SIGKILL'd mid-`cloud:up` leaves a GCP
89
90
  // instance with no docker/container, which the old (exists-only) matrix wrongly
90
- // classified 'reconcile-add' — adding an unreachable VM to the roster.
91
- // `containerUp` is only consulted for an add whose instance exists; destroy and
92
- // the instance-gone add path ignore it. Splitting the matrix out lets the table
93
- // be exhaustively tested without any of the side-effects in server.js.
94
- function reapVerdict({ action, exists, containerUp }) {
91
+ // classified 'reconcile-add' — adding an unreachable VM to the roster. The
92
+ // `projectWired` axis closes the remaining gap (improve39 VM-7): an instance +
93
+ // container that ARE up but whose `/workspace` is unwired (no git remote, empty
94
+ // manifest) is NOT a finished add — it's half-provisioned and must surface a
95
+ // recoverable card, not be silently reconciled "done". Only a POSITIVE unwired
96
+ // signal (`projectWired === false`) downgrades to 'half-provisioned'; an
97
+ // unknown/unprobed wiring (`null`/`undefined`) stays 'reconcile-add' so a flaky
98
+ // probe can't strand a healthy VM. `containerUp`/`projectWired` are only consulted
99
+ // for an add whose instance exists; destroy and the instance-gone add path ignore
100
+ // them. Splitting the matrix out lets the table be exhaustively tested without any
101
+ // of the side-effects in server.js.
102
+ function reapVerdict({ action, exists, containerUp, projectWired }) {
95
103
  if (exists === null) return 'leave';
96
104
  if (action === 'destroy') return exists ? 'clear-only' : 'cleanup';
97
105
  if (action === 'add') {
98
106
  if (!exists) return 'cleanup';
99
- return containerUp ? 'reconcile-add' : 'recover-bootstrap';
107
+ if (!containerUp) return 'recover-bootstrap';
108
+ return projectWired === false ? 'half-provisioned' : 'reconcile-add';
100
109
  }
101
110
  return 'leave';
102
111
  }
103
112
 
113
+ // Classify whether a VM's editor `/workspace` is actually wired to a client
114
+ // project, from a best-effort probe of two signals: the git remote URL and
115
+ // whether `package.json` carries a real `name`. Pure: server.js runs the SSH +
116
+ // `docker exec` probe and hands the raw stdout/err here so the decision is
117
+ // unit-testable without a live VM.
118
+ // - err present (ssh/docker blip, timeout) → null (unknown — do NOT
119
+ // strand a healthy VM on a flaky probe; reapVerdict treats null as wired)
120
+ // - a git remote OR a non-empty package.json name → true (wired)
121
+ // - neither (empty / no-git workspace) → false (half-provisioned —
122
+ // the VM-7 signature: `/workspace` with no remote and an empty manifest)
123
+ // The probe emits the two signals separated by the `---CY---` sentinel so this
124
+ // parser is independent of locale/line-ending noise in the ssh transport.
125
+ function classifyProjectWiring({ stdout, err } = {}) {
126
+ if (err) return null;
127
+ const parts = String(stdout == null ? '' : stdout).split('---CY---').map((s) => s.trim());
128
+ const remote = parts[0] || '';
129
+ const nameCount = Number((parts[1] || '0').trim()) || 0;
130
+ if (remote || nameCount > 0) return true;
131
+ return false;
132
+ }
133
+
134
+ // Durable exit marker for a detached `add` provision (improve40). The add's
135
+ // `cloud:up` shell is spawned in its OWN session (detached) so a dashboard
136
+ // SIGKILL — the 2GB launchd hard cap, exactly the kill that aborted the VM-7
137
+ // add mid-flight — no longer reaches it; the provision keeps running. When that
138
+ // detached shell finally exits it writes `add-<n>.exit` (its trailing exit code
139
+ // + an ISO timestamp) into PENDING_JOBS_DIR, alongside the `add-<n>.json`
140
+ // sidecar. The marker is the GROUND-TRUTH completion signal the next boot reads
141
+ // instead of inferring `in-flight → error` from the lost child: a marker means
142
+ // "the provision finished while the dashboard was away," its code says whether
143
+ // it finished OK. The name is derived here so the shell `trap` (server.js) and
144
+ // the JS reader build the exact same path.
145
+ function exitMarkerName(n) {
146
+ return `add-${n}.exit`;
147
+ }
148
+
149
+ // Parse an exit-marker file body into { exitCode, finishedAt }, or null when the
150
+ // body is missing/blank/malformed. Format is two lines — the numeric exit code
151
+ // then an ISO timestamp — written by the shell trap. A non-integer first line is
152
+ // treated as no-marker (null) so a half-written / corrupt marker falls back to
153
+ // the gcloud reconcile path rather than being read as a bogus exit code. Pure:
154
+ // takes the text so it's unit-testable without touching disk.
155
+ function parseExitMarker(text) {
156
+ if (text == null) return null;
157
+ const lines = String(text).split('\n').map((s) => s.trim()).filter(Boolean);
158
+ if (!lines.length) return null;
159
+ const code = Number(lines[0]);
160
+ if (!Number.isInteger(code)) return null;
161
+ return { exitCode: code, finishedAt: lines[1] || null };
162
+ }
163
+
164
+ // Read VM-n's exit marker from `dir`, or null when it's absent/unreadable/
165
+ // malformed (the still-running and never-written cases both surface as null).
166
+ function readExitMarker(dir, n) {
167
+ try { return parseExitMarker(fs.readFileSync(path.join(dir, exitMarkerName(n)), 'utf8')); }
168
+ catch { return null; }
169
+ }
170
+
171
+ // Remove a consumed exit marker; a missing file is the already-cleared path, not
172
+ // an error (mirrors clearPendingJob).
173
+ function clearExitMarker(dir, n) {
174
+ try { fs.unlinkSync(path.join(dir, exitMarkerName(n))); }
175
+ catch (_) { /* missing is fine */ }
176
+ }
177
+
178
+ // Decide how a snapshot-restored `add` should be re-attached after a dashboard
179
+ // restart, BEFORE any gcloud probe. Pure: takes the durable signals the boot
180
+ // path gathers — whether the exit marker exists, its recorded code, and whether
181
+ // the detached provision child is still alive (recorded pid, `kill -0`).
182
+ // verdict when dispatch
183
+ // 'done' marker present, exit code 0 roster + recordLaunch, clear sidecar/marker
184
+ // 'error' marker present, non-zero exit code surface the real failure, clear sidecar/marker
185
+ // 'running' no marker yet, child still alive RE-ATTACH: keep polling, do NOT mark error
186
+ // 'reconcile' child gone, no usable marker fall through to fc.reapVerdict (gcloud probe)
187
+ // This is the durable fix's brain: a provision that survived the kill (still
188
+ // running, or finished while we were away) is classified from GROUND TRUTH, so
189
+ // it is never blanket-converted `in-flight → error` the way the snapshot-only
190
+ // path did (the improve39 VM-7 false `add-failed`). Only when the child is gone
191
+ // AND left no parseable marker do we fall back to inferring state from gcloud —
192
+ // `reconcile` hands that exact (exists, containerUp, projectWired) decision to
193
+ // fc.reapVerdict. A marker whose first line isn't an integer is treated as
194
+ // absent (parseExitMarker → null) so a corrupt marker reconciles rather than
195
+ // asserting a bogus code. The matrix is exhaustively tested without a live VM.
196
+ function reattachVerdict({ markerPresent, exitCode, childAlive } = {}) {
197
+ if (markerPresent) {
198
+ // Guard the null/undefined coercion BEFORE Number() — `Number(null)` is 0,
199
+ // which would masquerade as a clean exit. A marker with no parseable code
200
+ // (half-written / corrupt) must reconcile, not assert success.
201
+ const code = exitCode == null ? NaN : Number(exitCode);
202
+ if (Number.isInteger(code)) return code === 0 ? 'done' : 'error';
203
+ return 'reconcile'; // marker present but no parseable code — let gcloud decide
204
+ }
205
+ if (childAlive) return 'running';
206
+ return 'reconcile';
207
+ }
208
+
104
209
  // Anti-loop budget for the `recover-bootstrap` path. Pure: given the count of
105
210
  // recoveries ALREADY persisted on the sidecar, return the next attempt number,
106
211
  // whether the reap should proceed (re-run cloud:up) or treat the VM as
@@ -113,6 +218,66 @@ function recoverBootstrapDecision({ recoverAttempts, max = 3 }) {
113
218
  return { attempt, proceed: attempt <= max, max };
114
219
  }
115
220
 
221
+ // improve40 — select the orphaned `add` jobs that must be reconciled from the
222
+ // VM's REAL provision state even though their per-job sidecar is GONE. The
223
+ // durable re-attach path (sidecar + exit marker + recorded pid) cannot fire for
224
+ // these — a restart left only the snapshot record — so the snapshot job's
225
+ // stashed `config` is the sole cfg source and a live gcloud probe is the only
226
+ // ground truth. Pure: takes the restored jobs map + the set of `<action>-<n>`
227
+ // sidecar keys the sidecar reap already owns; returns the [{ n, cfg }] the boot
228
+ // path hands to reconcileViaGcloud. A job is selected when ALL hold:
229
+ // - it is an `add`,
230
+ // - it is flagged `restartOrphaned` (restoreFromSnapshot downgraded a
231
+ // running add → error because the dashboard restarted before it finished —
232
+ // this is the ONLY error state we re-probe; an add that failed IN-PROCESS
233
+ // carries a plain terminal `error` with no flag and stays surfaced), AND
234
+ // - NO `add-<n>` sidecar exists (a sidecar means the sidecar reap already
235
+ // owns it — never double-reconcile).
236
+ // `cfg` rides from the job's `config`; null when the snapshot never carried one
237
+ // (older snapshot) — the caller still probes, but a roster reconcile then can't
238
+ // recordLaunch, exactly mirroring the sidecar path's `meta.cfg`-absent case.
239
+ function orphanedAddsToReconcile({ jobs, sidecarKeys } = {}) {
240
+ const sidecars = sidecarKeys instanceof Set ? sidecarKeys : new Set(sidecarKeys || []);
241
+ const src = (jobs && typeof jobs === 'object') ? jobs : {};
242
+ const out = [];
243
+ for (const [k, j] of Object.entries(src)) {
244
+ if (!j || typeof j !== 'object') continue;
245
+ if (j.action !== 'add') continue;
246
+ if (!j.restartOrphaned) continue;
247
+ if (sidecars.has(`add-${k}`)) continue;
248
+ out.push({ n: Number(k), cfg: j.config || null });
249
+ }
250
+ return out;
251
+ }
252
+
253
+ // improve41 — the destroy-direction mirror of orphanedAddsToReconcile: decide
254
+ // what to do with a VM that is STILL in the roster but whose GCP instance state
255
+ // we have just re-probed. The bug this closes: a Destroy that races a dashboard
256
+ // restart can leave the instance deleted while the startup reap took the
257
+ // `clear-only` path (instance still present at reap time) and dropped the only
258
+ // sidecar — so nothing ever runs roster cleanup and the VM polls forever
259
+ // "unreachable." A sidecar-independent reconcile, keyed on REAL GCP existence
260
+ // rather than on a pending-job sidecar, catches it. Pure: server.js runs the
261
+ // gcloud describe (→ exists, via classifyDescribeError) and reads session /
262
+ // pending-add state, and hands the three facts here so the matrix is testable
263
+ // without a live VM.
264
+ // verdict when dispatch
265
+ // 'cleanup' instance gone AND the VM is idle runDestroyCleanup
266
+ // 'leave' exists uncertain (null), OR the VM is busy do nothing this pass
267
+ // 'keep' instance still exists do nothing (healthy)
268
+ // Fail-safe by construction: cleanup fires ONLY on a DEFINITIVE absence
269
+ // (exists === false) — a flaky/transient describe (null) is always 'leave', so a
270
+ // gcloud blip can never evict a healthy VM (mirroring reapVerdict's `leave`
271
+ // posture). "Busy" (a live session or an in-flight add to this number) also
272
+ // holds the entry for an operator rather than auto-removing — the shouldn't-
273
+ // happen-but-fail-safe case where a vanished instance still reports a session.
274
+ function reconcileRosteredVm({ exists, hasSession, hasPendingAdd } = {}) {
275
+ if (exists === null || exists === undefined) return "leave";
276
+ if (exists) return "keep";
277
+ if (hasSession || hasPendingAdd) return "leave";
278
+ return "cleanup";
279
+ }
280
+
116
281
  module.exports = {
117
282
  parsePendingJobFilename,
118
283
  persistPendingJob,
@@ -120,5 +285,13 @@ module.exports = {
120
285
  listPendingJobs,
121
286
  classifyDescribeError,
122
287
  reapVerdict,
288
+ reconcileRosteredVm,
289
+ orphanedAddsToReconcile,
290
+ classifyProjectWiring,
123
291
  recoverBootstrapDecision,
292
+ exitMarkerName,
293
+ parseExitMarker,
294
+ readExitMarker,
295
+ clearExitMarker,
296
+ reattachVerdict,
124
297
  };
@@ -0,0 +1,179 @@
1
+ 'use strict';
2
+ // Pure predicate module for the Fleet Dashboard's per-button "will clicking
3
+ // this change the VM, or is it already in that state?" indicators
4
+ // (scripts/operator/fleet-dashboard/server.js requires this). Given an
5
+ // already-gathered FACTS object — no I/O, no git/docker exec; server.js does
6
+ // the impure fact-gathering — computeButtonEffects returns a per-button verdict
7
+ // map. Mirrors the pure-module-plus-colocated-vitest-test shape of
8
+ // npm/fleet-reset.js so the whole decision table is unit-testable without
9
+ // spawning a process.
10
+ //
11
+ // Each verdict is { effect, reason }:
12
+ // - 'changes' — clicking does something; `reason` says what.
13
+ // - 'noop' — already in that state; clicking changes nothing.
14
+ // - 'recommended' — soft signal (run-setup only): a reset/update landed after
15
+ // the last successful setup. NEVER a confident green no-op.
16
+ // - 'unknown' — not yet checked, VM unreachable, or a needed fact is
17
+ // missing. We never CLAIM a safe no-op we couldn't verify —
18
+ // silent failure here would be worse than no indicator.
19
+ //
20
+ // The predicate for each button is derived from what that button actually
21
+ // touches (its tooltip in public/index.html is the source of truth): the sync
22
+ // buttons key off a git commit comparison, the reset buttons off
23
+ // working-tree/session/`.codeyam` state, and rebuild off a build-commit
24
+ // comparison.
25
+
26
+ // Short sha for compact reason strings. Tolerates null / short input.
27
+ function short(sha) {
28
+ return sha ? String(sha).slice(0, 7) : '?';
29
+ }
30
+
31
+ // "origin/<branch>" — or a bare "origin" when the branch is unknown.
32
+ function originRef(branch) {
33
+ return branch ? `origin/${branch}` : 'origin';
34
+ }
35
+
36
+ // "N commit(s) behind origin/<branch>" with correct singular/plural.
37
+ function behindReason(behind, branch) {
38
+ return `${behind} commit${behind === 1 ? '' : 's'} behind ${originRef(branch)}`;
39
+ }
40
+
41
+ // Compose a short reason listing which signals make a reset non-trivial, so the
42
+ // operator sees WHAT a Reset would discard rather than a bare "changes". The
43
+ // `agent` (a live build agent in the broker) leads the list — it's the most
44
+ // consequential thing a reset's `pty-broker stop` would silently discard.
45
+ function resetReason({ agent, session, dirty, behind, codeyam }) {
46
+ const parts = [];
47
+ if (agent) parts.push('running build agent');
48
+ if (dirty) parts.push('uncommitted changes');
49
+ if (behind) parts.push('source behind origin');
50
+ if (session) parts.push('active session');
51
+ if (codeyam) parts.push('.codeyam state');
52
+ return parts.length ? `will discard: ${parts.join(', ')}` : 'will reset state';
53
+ }
54
+
55
+ // The action ids governed by an effect indicator — the same ids server.js /
56
+ // index.html use for the buttons. Reconfigure / Env / Destroy are deliberately
57
+ // absent (one-shots, not converge-to-a-state actions, so a no-op predicate is
58
+ // meaningless for them).
59
+ const ACTION_IDS = [
60
+ 'update-client-source',
61
+ 'update-editor-source',
62
+ 'reset-editor-source',
63
+ 'reset-client',
64
+ 'rebuild-binary',
65
+ 'update-reset-everything',
66
+ 'run-setup',
67
+ ];
68
+
69
+ // facts (a plain object gathered by server.js — no I/O):
70
+ // {
71
+ // reachable: boolean,
72
+ // hasSession: boolean,
73
+ // client: { headSha, originSha, behind, dirty } | null, // /workspace
74
+ // editor: { headSha, originSha, behind, dirty, buildCommit } | null,
75
+ // codeyamDirty: boolean,
76
+ // setupRanSince: boolean, // a setup completed after the last reset/update
77
+ // clientBranch: string | null, // for reason text only
78
+ // editorBranch: string | null, // for reason text only
79
+ // }
80
+ function computeButtonEffects(facts) {
81
+ const f = facts || {};
82
+
83
+ // Unreachable VM (or no facts at all): every governed button is unknown. We
84
+ // could not reach the editor to gather facts, so never render a green no-op.
85
+ if (!f.reachable) {
86
+ const out = {};
87
+ for (const id of ACTION_IDS) out[id] = { effect: 'unknown', reason: 'VM unreachable' };
88
+ return out;
89
+ }
90
+
91
+ const client = f.client || null;
92
+ const editor = f.editor || null;
93
+ const hasSession = !!f.hasSession;
94
+ const codeyamDirty = !!f.codeyamDirty;
95
+ // A live build agent in the broker. A reset's first step is `pty-broker stop`,
96
+ // which kills it regardless of whether a workflow session is registered — so
97
+ // this is discardable work even when hasSession is false. Explicit-true only:
98
+ // a null/absent value (older or unreachable VM) must NOT flip a genuine noop.
99
+ const brokerLive = f.brokerLive === true;
100
+
101
+ // (1) Update client — ff-advance /workspace to origin tip. Changes iff behind.
102
+ const updateClient = client == null
103
+ ? { effect: 'unknown', reason: 'client state not checked' }
104
+ : client.behind > 0
105
+ ? { effect: 'changes', reason: behindReason(client.behind, f.clientBranch) }
106
+ : { effect: 'noop', reason: 'up to date with ' + originRef(f.clientBranch) };
107
+
108
+ // (2) Update editor — advance the editor source the binary builds from.
109
+ const updateEditor = editor == null
110
+ ? { effect: 'unknown', reason: 'editor state not checked' }
111
+ : editor.behind > 0
112
+ ? { effect: 'changes', reason: behindReason(editor.behind, f.editorBranch) }
113
+ : { effect: 'noop', reason: 'up to date with ' + originRef(f.editorBranch) };
114
+
115
+ // (5) Rebuild binary — advances source then compiles. Changes iff the running
116
+ // binary's build commit differs from the editor origin tip. Unknown when we
117
+ // don't have both commits to compare.
118
+ const rebuild = (editor == null || !editor.buildCommit || !editor.originSha)
119
+ ? { effect: 'unknown', reason: 'binary/source commit not checked' }
120
+ : editor.buildCommit !== editor.originSha
121
+ ? { effect: 'changes', reason: `binary at ${short(editor.buildCommit)}, ${originRef(f.editorBranch)} at ${short(editor.originSha)}` }
122
+ : { effect: 'noop', reason: 'binary built from ' + originRef(f.editorBranch) + ' tip' };
123
+
124
+ // (3) Reset editor — discards uncommitted + session, advances source, wipes
125
+ // .codeyam. No-op ONLY when clean at origin tip with no session.
126
+ const resetEditor = editor == null
127
+ ? { effect: 'unknown', reason: 'editor state not checked' }
128
+ : (brokerLive || hasSession || editor.dirty || editor.behind > 0 || codeyamDirty)
129
+ ? { effect: 'changes', reason: resetReason({ agent: brokerLive, session: hasSession, dirty: editor.dirty, behind: editor.behind > 0, codeyam: codeyamDirty }) }
130
+ : { effect: 'noop', reason: 'already clean at origin tip, no session' };
131
+
132
+ // (3b) Reset client — hard-clean /workspace + .codeyam, drop the session.
133
+ // No source-advance, so `behind` is NOT part of this predicate.
134
+ const resetClient = client == null
135
+ ? { effect: 'unknown', reason: 'client state not checked' }
136
+ : (brokerLive || client.dirty || codeyamDirty || hasSession)
137
+ ? { effect: 'changes', reason: resetReason({ agent: brokerLive, session: hasSession, dirty: client.dirty, behind: false, codeyam: codeyamDirty }) }
138
+ : { effect: 'noop', reason: 'already clean, no session' };
139
+
140
+ // (4b) Update & Reset Everything — composite. Changes iff ANY component would
141
+ // change: rebuild-binary, reset-editor-source, or the client being
142
+ // behind/dirty. Reason summarizes which parts.
143
+ const everything = (() => {
144
+ if (editor == null || client == null) {
145
+ return { effect: 'unknown', reason: 'state not checked' };
146
+ }
147
+ const parts = [];
148
+ if (rebuild.effect === 'changes') parts.push('rebuild');
149
+ if (resetEditor.effect === 'changes') parts.push('reset editor');
150
+ if (client.behind > 0 || client.dirty) parts.push('reset client');
151
+ if (parts.length > 0) return { effect: 'changes', reason: parts.join(' + ') };
152
+ // No part would change. But if a component was itself unverifiable, don't
153
+ // claim a confident no-op — fall back to unknown.
154
+ if (rebuild.effect === 'unknown' || resetEditor.effect === 'unknown') {
155
+ return { effect: 'unknown', reason: 'state not checked' };
156
+ }
157
+ return { effect: 'noop', reason: 'everything already at origin tip, no session' };
158
+ })();
159
+
160
+ // (run-setup) Honest soft signal — there is no cheap upstream proof that
161
+ // `npm run setup` would change nothing (DB/migration state isn't
162
+ // introspected). `recommended` when a reset/update landed after the last
163
+ // successful setup; otherwise `unknown`. Never a confident green no-op.
164
+ const runSetup = f.setupRanSince
165
+ ? { effect: 'unknown', reason: 'no setup-affecting change since last setup' }
166
+ : { effect: 'recommended', reason: 'a reset/update landed since the last setup' };
167
+
168
+ return {
169
+ 'update-client-source': updateClient,
170
+ 'update-editor-source': updateEditor,
171
+ 'reset-editor-source': resetEditor,
172
+ 'reset-client': resetClient,
173
+ 'rebuild-binary': rebuild,
174
+ 'update-reset-everything': everything,
175
+ 'run-setup': runSetup,
176
+ };
177
+ }
178
+
179
+ module.exports = { computeButtonEffects, ACTION_IDS };
@@ -0,0 +1,56 @@
1
+ // Group an already-sorted/filtered VM list by client project for the Fleet
2
+ // Dashboard's grouped layout.
3
+ //
4
+ // Returns an ORDERED array of { project, vms } groups: real project groups
5
+ // first, sorted case-insensitively by name (locale compare); the
6
+ // unknown/starting-up bucket (project === null) pinned LAST. Within each group
7
+ // the incoming order of `vms` is preserved untouched, so the caller's active
8
+ // Sort mode continues to drive within-group order — grouping never re-sorts the
9
+ // cards, it only partitions them.
10
+ //
11
+ // `projectKey(v)` resolves the group key for a VM and defaults to the same
12
+ // identity `card()` renders in the dashboard:
13
+ // (v.cardIdentity && v.cardIdentity.project) || v.project || null
14
+ // It is injectable so unit tests can drive grouping without constructing full
15
+ // card payloads. A null/empty key routes the VM into the trailing unknown
16
+ // bucket so VMs mid-provision (blank identity) never silently disappear.
17
+ //
18
+ // Pure; no I/O.
19
+
20
+ function defaultProjectKey(v) {
21
+ return (v && v.cardIdentity && v.cardIdentity.project) || (v && v.project) || null;
22
+ }
23
+
24
+ function groupVmsByProject(vms, projectKey = defaultProjectKey) {
25
+ // First pass: stable bucketing. `Map` preserves insertion order, so the
26
+ // first VM of each project fixes that group's relative position before we
27
+ // re-order — but we re-sort named groups below regardless, so insertion
28
+ // order only matters for tie-stability within equal-name groups (none here).
29
+ const named = new Map();
30
+ let unknown = null;
31
+
32
+ for (const v of vms) {
33
+ const raw = projectKey(v);
34
+ const key = raw == null || raw === "" ? null : raw;
35
+ if (key === null) {
36
+ if (!unknown) unknown = { project: null, vms: [] };
37
+ unknown.vms.push(v);
38
+ continue;
39
+ }
40
+ let group = named.get(key);
41
+ if (!group) {
42
+ group = { project: key, vms: [] };
43
+ named.set(key, group);
44
+ }
45
+ group.vms.push(v);
46
+ }
47
+
48
+ const groups = Array.from(named.values());
49
+ groups.sort((a, b) =>
50
+ a.project.localeCompare(b.project, undefined, { sensitivity: "base" })
51
+ );
52
+ if (unknown) groups.push(unknown);
53
+ return groups;
54
+ }
55
+
56
+ module.exports = { groupVmsByProject, defaultProjectKey };
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+
3
+ // npm/fleet-job-badge.js — pure verdict for the fleet dashboard's failed-job
4
+ // badge reconciliation (improve39). A VM's last terminal-error heavy job
5
+ // (add/error, reset-all error, reset-editor error, …) used to stick on the
6
+ // dashboard card indefinitely — even after the VM was recovered and is healthy
7
+ // again — because the card renders the last job's error with no check against
8
+ // the VM's live state, so a recovered VM keeps screaming a red error and
9
+ // misleads the operator. This decides whether such a badge should be RECONCILED
10
+ // (presented as "recovered" rather than a live error) because the VM is
11
+ // demonstrably fine now. The live signals are gathered in server.js (the
12
+ // untestable server shell); the verdict lives here so the cases are unit-tested
13
+ // without a live VM.
14
+
15
+ // Should the VM's last terminal-error job badge be reconciled against live
16
+ // health — i.e. presented as "recovered" rather than a live red error?
17
+ //
18
+ // job the carried job record ({ state, action, ... }) or null
19
+ // reachable the VM's editor answered this poll (true = healthy / responding)
20
+ // drifted a project-dir-drift signal is present (reachable-but-unwired /
21
+ // half-provisioned add — genuinely needs-recovery, owned by the
22
+ // companion reconcile-inflight-jobs plan; never falsely cleared here)
23
+ // offBranch the VM's live client branch differs from its target branch
24
+ // degraded the job completed but a wiring sub-step is flagged degraded
25
+ //
26
+ // Returns true only when the job is a terminal error AND the VM is demonstrably
27
+ // fine (reachable, not drifted, on-branch, not degraded). An unreachable /
28
+ // drifted / off-branch VM keeps its error surfaced — a real problem must stay
29
+ // visible.
30
+ function shouldReconcileFailedBadge({ job, reachable, drifted, offBranch, degraded } = {}) {
31
+ if (!job || job.state !== 'error') return false;
32
+ if (!reachable) return false;
33
+ if (drifted) return false;
34
+ if (offBranch) return false;
35
+ if (degraded) return false;
36
+ return true;
37
+ }
38
+
39
+ module.exports = { shouldReconcileFailedBadge };
@@ -74,17 +74,30 @@ function decodeStateSnapshot(buf) {
74
74
  * Returns null when the snapshot is missing, malformed, or older than
75
75
  * maxAgeMs (stale snapshots are worse than no snapshot — pollVMs will
76
76
  * repopulate from real data). Otherwise returns { jobs, vms, orphans }
77
- * with two safety transforms applied to jobs:
77
+ * with these safety transforms applied to jobs:
78
78
  *
79
- * • `running` → `error` with a log marker, because the child process
80
- * died with the dashboard; we can't possibly have a live job tracker
81
- * after a process restart.
79
+ * • `running` WITH a pending-job sidecar → `recovering` with a deferral
80
+ * marker, NOT `error`. A heavy job that stashed a recoverable sidecar
81
+ * (its cfg) must defer its final state to the startup reap, which
82
+ * actually checks gcloud — the blanket `error` was the improve39 VM-7
83
+ * bug: a mid-add restart stranded an instance that was really up as a
84
+ * dead `add-failed`. `recovering` is an honest "the reap will resolve
85
+ * this" surface; the reap then supersedes it (reconcile/half-provisioned
86
+ * /cleanup) once it has the gcloud verdict.
87
+ * • `running` WITHOUT a sidecar → `error` with a log marker, because the
88
+ * child process died with the dashboard and there's nothing to recover
89
+ * from — un-recoverable history, the old behavior.
82
90
  * • `queued` → dropped, because the in-memory pendingJobQueue array
83
91
  * is gone, so promoteFromJobQueue can never start them. The operator
84
92
  * will re-click (the queued click had done no work yet).
85
93
  *
94
+ * `sidecarKeys` is the set of `${action}-${n}` strings the caller read from
95
+ * the pending-jobs dir (server.js passes it; tests pass a plain array/Set).
96
+ * Omitted → no job has a sidecar → every running job downgrades to `error`
97
+ * exactly as before, so existing callers/tests are unaffected.
98
+ *
86
99
  * Pure; no I/O. */
87
- function restoreFromSnapshot({ snapshot, maxAgeMs, nowIso } = {}) {
100
+ function restoreFromSnapshot({ snapshot, maxAgeMs, nowIso, sidecarKeys } = {}) {
88
101
  if (!snapshot || typeof snapshot !== 'object') return null;
89
102
  if (typeof snapshot.timestamp !== 'string') return null;
90
103
  const ts = Date.parse(snapshot.timestamp);
@@ -95,16 +108,33 @@ function restoreFromSnapshot({ snapshot, maxAgeMs, nowIso } = {}) {
95
108
  if (!Number.isFinite(cap) || cap <= 0) return null;
96
109
  if (ageMs > cap) return null;
97
110
 
111
+ const sidecars = sidecarKeys instanceof Set ? sidecarKeys : new Set(sidecarKeys || []);
98
112
  const srcJobs = (snapshot.jobs && typeof snapshot.jobs === 'object') ? snapshot.jobs : {};
99
113
  const jobs = {};
100
114
  for (const [k, j] of Object.entries(srcJobs)) {
101
115
  if (!j || typeof j !== 'object') continue;
102
116
  if (j.state === 'queued') continue;
103
117
  if (j.state === 'running') {
118
+ if (sidecars.has(`${j.action}-${k}`)) {
119
+ jobs[k] = {
120
+ ...j,
121
+ state: 'recovering',
122
+ log: `${j.log ? j.log + '\n' : ''}(snapshot-restored — deferring to startup reap)`,
123
+ };
124
+ continue;
125
+ }
104
126
  jobs[k] = {
105
127
  ...j,
106
128
  state: 'error',
107
129
  finishedAt: nowIso,
130
+ // improve40: mark this as a restart-orphan, NOT a genuine in-process
131
+ // failure. The job was `running` when the restart downgraded it and has
132
+ // NO sidecar to reconcile from — so the boot path must probe the VM's
133
+ // REAL provision state (orphanedAddsToReconcile → gcloud reap) rather
134
+ // than leave a dead `add-failed` badge on a VM that may have actually
135
+ // provisioned (the VM-7 hole). An add that failed IN-PROCESS keeps its
136
+ // own terminal `error` with no flag, so it is never re-probed/cleared.
137
+ restartOrphaned: true,
108
138
  log: `${j.log ? j.log + '\n' : ''}(snapshot-restored — dashboard restarted before this finished)`,
109
139
  };
110
140
  continue;