Repository navigation
Expand file tree
/
Copy pathvortexVote.js
More file actions
524 lines (468 loc) · 22.7 KB
/
Copy pathvortexVote.js
File metadata and controls
524 lines (468 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/**
* vortexVote.js
* ═══════════════════════════════════════════════════════════════════════
* A JavaScript/Bun module implementing the "369 Vortex Vote" consensus
* *metaphor*: three threshold-gating decision rules for deciding whether
* an action should proceed, given collected votes.
*
* This is NOT a distributed consensus protocol (no networking, no fault
* model, no liveness/safety proofs). It's a rules engine for "should this
* thing happen?" decisions, borrowing consensus vocabulary as a design
* frame — see the accompanying whitepaper for the formal analysis.
*
* ── FORMAL MODEL ──────────────────────────────────────────────────────
* Each path P is a function:
* P : V₁ × V₂ × ... × Vₖ → Result<Decision, VortexVoteError>
* where Decision = { outcome: Outcome, details: object }
*
* Malformed input (wrong shape, wrong arity, unknown enum
* values) is NOT silently coerced into a business outcome like ABORT.
* It is distinguished at the boundary as Err(VortexVoteError) — a
* programmer/caller error — separately from Ok({outcome: ABORT, ...}),
* which is a legitimate vote result. Conflating the two is the
* classic NSF (No Silent Failure) violation this module is designed to avoid.
*
* ── TABLE OF CONTENTS ─────────────────────────────────────────────────
* §1 Result type & error taxonomy
* §2 Outcome / VoteState / VotePath enums
* §3 Validation helpers (fail fast, typed, at the boundary)
* §4 Shared vote-counting helpers
* §5 FAST PATH (3-4-1/3)
* §6 MIDDLE PATH (3-6-9) — includes the cyclic-audit fix
* §7 SLOW PATH (7-4-?)
* §8 runVote() dispatcher
* §9 Bun demo runner
*
* ── NO PHASE LOCKS ────────────────────────────────────────────────────
* Every exported function here is pure and stateless — no shared
* mutable state, no mutex-like gating, no requirement that callers
* invoke functions in a particular order across calls. The one place
* that could superficially resemble a phase sequence — the 9-round
* cyclic audit — wasn't actually independent per round (it re-read a
* static array 9 times). §6 fixes that: callers may now supply a
* `pollFn` so each round is a genuine, independent observation. With
* no `pollFn`, behavior is still deterministic and side-effect-free.
* ═══════════════════════════════════════════════════════════════════════
*/
// ───────────────────────────────────────────────────────────────────────
// §1 — Result type & error taxonomy
// ───────────────────────────────────────────────────────────────────────
/** @template T @param {T} value @returns {{ok: true, value: T}} */
export function Ok(value) {
return { ok: true, value };
}
/** @template E @param {E} error @returns {{ok: false, error: E}} */
export function Err(error) {
return { ok: false, error };
}
export function isOk(result) {
return result?.ok === true;
}
export function isErr(result) {
return result?.ok === false;
}
/**
* Unwraps a Result, throwing if it's an Err. Use only at the outermost
* edge of a program (e.g. a CLI entrypoint) where an unhandled error
* should genuinely crash — never inside library code.
*/
export function unwrap(result) {
if (isOk(result)) return result.value;
throw result.error instanceof Error ? result.error : new Error(String(result.error));
}
export const ErrorCode = Object.freeze({
INVALID_VOTE_ARRAY: "INVALID_VOTE_ARRAY",
INVALID_VOTE_ENTRY: "INVALID_VOTE_ENTRY",
INVALID_GATE_ARRAY: "INVALID_GATE_ARRAY",
INVALID_STATE_VALUE: "INVALID_STATE_VALUE",
INVALID_PATH: "INVALID_PATH",
});
export class VortexVoteError extends Error {
/**
* @param {string} code - one of ErrorCode
* @param {string} message
* @param {object} [context] - the offending field/value, for debugging
*/
constructor(code, message, context = {}) {
super(message);
this.name = "VortexVoteError";
this.code = code;
this.context = context;
}
}
// ───────────────────────────────────────────────────────────────────────
// §2 — Enums
// ───────────────────────────────────────────────────────────────────────
export const Outcome = Object.freeze({
ABORT: "ABORT",
COMMIT: "COMMIT",
ROLLBACK: "ROLLBACK",
RECONCILE: "RECONCILE",
HOLD: "HOLD",
HUMAN_REVIEW: "HUMAN_REVIEW",
DELAY_AND_AUDIT: "DELAY_AND_AUDIT",
SAFE_COMMIT: "SAFE_COMMIT",
});
// The 7 discrete states used by the slow path
export const VoteState = Object.freeze({
YES: "yes",
NO: "no",
MAYBE: "maybe",
WAIT: "wait",
ESCALATE: "escalate",
REJECT: "reject",
AUDIT: "audit",
});
export const VotePath = Object.freeze({
FAST: "fast",
MIDDLE: "middle",
SLOW: "slow",
});
const VALID_VOTE_STATES = new Set(Object.values(VoteState));
// ───────────────────────────────────────────────────────────────────────
// §3 — Validation helpers
// Every one of these fails fast with a typed VortexVoteError instead of
// letting a malformed call silently fall through into business logic.
// ───────────────────────────────────────────────────────────────────────
/**
* Validates a vote array: must be an Array, at least `minLength` long,
* and every entry must be an object with a `.vote` field that is one of
* "accept" | "reject" | true | false.
*
* @returns {{ok: true, value: Array}|{ok: false, error: VortexVoteError}}
*/
function validateVoteArray(votes, minLength, fieldName) {
if (!Array.isArray(votes)) {
return Err(new VortexVoteError(
ErrorCode.INVALID_VOTE_ARRAY,
`${fieldName} must be an array, got ${votes === null ? "null" : typeof votes}`,
{ fieldName, received: votes }
));
}
if (votes.length < minLength) {
return Err(new VortexVoteError(
ErrorCode.INVALID_VOTE_ARRAY,
`${fieldName} must have at least ${minLength} entries, got ${votes.length}`,
{ fieldName, minLength, received: votes.length }
));
}
for (let i = 0; i < votes.length; i++) {
const v = votes[i];
const validVote = v && typeof v === "object" &&
(v.vote === "accept" || v.vote === "reject" || v.vote === true || v.vote === false);
if (!validVote) {
return Err(new VortexVoteError(
ErrorCode.INVALID_VOTE_ENTRY,
`${fieldName}[${i}] must be an object with vote: "accept"|"reject"|true|false`,
{ fieldName, index: i, received: v }
));
}
}
return Ok(votes);
}
/**
* Validates the 4 structural gate checks: must be an Array of at least
* 4 booleans (extra entries beyond 4 are ignored downstream).
*/
function validateGateArray(gateChecks) {
if (!Array.isArray(gateChecks)) {
return Err(new VortexVoteError(
ErrorCode.INVALID_GATE_ARRAY,
`gateChecks must be an array, got ${gateChecks === null ? "null" : typeof gateChecks}`,
{ received: gateChecks }
));
}
if (gateChecks.length < 4) {
return Err(new VortexVoteError(
ErrorCode.INVALID_GATE_ARRAY,
`gateChecks must have at least 4 entries, got ${gateChecks.length}`,
{ received: gateChecks.length }
));
}
const nonBooleanIdx = gateChecks.slice(0, 4).findIndex((g) => typeof g !== "boolean");
if (nonBooleanIdx !== -1) {
return Err(new VortexVoteError(
ErrorCode.INVALID_GATE_ARRAY,
`gateChecks[${nonBooleanIdx}] must be a boolean`,
{ index: nonBooleanIdx, received: gateChecks[nonBooleanIdx] }
));
}
return Ok(gateChecks);
}
/**
* Validates the slow path's discrete state votes: must be an Array where
* every entry is one of the 7 canonical VoteState values. An unrecognized
* string here is almost always a caller typo (e.g. "yess") — left
* unvalidated, it would silently fall through to majorityYes()===false
* and end up as an ordinary ABORT, indistinguishable from a genuine
* "no" vote.
*/
function validateStateVotes(stateVotes) {
if (!Array.isArray(stateVotes)) {
return Err(new VortexVoteError(
ErrorCode.INVALID_VOTE_ARRAY,
`stateVotes must be an array, got ${stateVotes === null ? "null" : typeof stateVotes}`,
{ received: stateVotes }
));
}
for (let i = 0; i < stateVotes.length; i++) {
if (!VALID_VOTE_STATES.has(stateVotes[i])) {
return Err(new VortexVoteError(
ErrorCode.INVALID_STATE_VALUE,
`stateVotes[${i}] must be one of ${[...VALID_VOTE_STATES].join(", ")}; got ${JSON.stringify(stateVotes[i])}`,
{ index: i, received: stateVotes[i] }
));
}
}
return Ok(stateVotes);
}
// ───────────────────────────────────────────────────────────────────────
// §4 — Shared vote-counting helpers (operate only on already-validated input)
// ───────────────────────────────────────────────────────────────────────
function hasQuorum(votes, min = votes.length) {
const accepted = votes.filter((v) => v.vote === "accept" || v.vote === true);
return accepted.length >= min;
}
function countAccepts(votes) {
return votes.filter((v) => v.vote === "accept" || v.vote === true).length;
}
function takeFirst(votes, n) {
return votes.slice(0, n);
}
// ───────────────────────────────────────────────────────────────────────
// §5 — FAST PATH: 3-4-1/3
// 3 primary voters -> 4 stabilizers -> commit if >=1/3 of stabilizers accept
// ───────────────────────────────────────────────────────────────────────
/**
* @param {Array<{vote: string|boolean}>} primaryVotes - exactly 3 or more; first 3 used
* @param {Array<{vote: string|boolean}>} stabilizerVotes - exactly 4 or more; first 4 used
* @returns {{ok:true, value:{outcome:string, details:object}}|{ok:false, error:VortexVoteError}}
*/
export function fastPath(primaryVotes, stabilizerVotes) {
const primaryCheck = validateVoteArray(primaryVotes, 3, "primaryVotes");
if (isErr(primaryCheck)) return primaryCheck;
const stabilizerCheck = validateVoteArray(stabilizerVotes, 4, "stabilizerVotes");
if (isErr(stabilizerCheck)) return stabilizerCheck;
const primary = takeFirst(primaryCheck.value, 3);
if (!hasQuorum(primary, 3)) {
return Ok({ outcome: Outcome.ABORT, details: { reason: "no primary quorum" } });
}
const stabilizers = takeFirst(stabilizerCheck.value, 4);
const acceptCount = countAccepts(stabilizers);
// Threshold is relative to the actual stabilizer arity, not a hardcoded
// literal — fixes the fast-path arity coupling flagged in the whitepaper.
const threshold = Math.ceil(stabilizers.length * (1 / 3));
if (acceptCount >= threshold) {
return Ok({ outcome: Outcome.COMMIT, details: { acceptCount, threshold } });
}
return Ok({ outcome: Outcome.ROLLBACK, details: { acceptCount, threshold } });
}
// ───────────────────────────────────────────────────────────────────────
// §6 — MIDDLE PATH: 3-6-9
// 3 seed voters -> 6 validators -> 9 cyclic auditors
// ───────────────────────────────────────────────────────────────────────
/**
* Runs a cyclic audit over `validators`, producing `auditCount` pass/fail
* rounds (default 9). A round "passes" if a majority of that round's
* validator snapshot accepts.
*
* A naive implementation re-checks the *same static* array every round,
* so `passes` would always be 0 or `auditCount` — never anything in
* between. This function instead accepts an optional
* `pollFn(round, validators) => Array<{vote}>` so each round can
* be a genuinely independent observation (e.g. re-polling live agents).
* With no `pollFn`, behavior stays deterministic and side-effect-free.
*
* @param {Array<{vote: string|boolean}>} validators
* @param {number} [auditCount=9]
* @param {(round:number, validators:Array) => Array<{vote:string|boolean}>} [pollFn]
* @returns {{passes:number, rounds:Array<boolean>}}
*/
export function runCyclicAudit(validators, auditCount = 9, pollFn = null) {
const rounds = [];
for (let round = 0; round < auditCount; round++) {
const snapshot = pollFn ? pollFn(round, validators) : validators;
const acceptCount = countAccepts(snapshot);
rounds.push(acceptCount > snapshot.length / 2);
}
const passes = rounds.filter(Boolean).length;
return { passes, rounds };
}
/**
* @param {Array<{vote: string|boolean}>} seedVotes - 3 seed voters
* @param {Array<{vote: string|boolean}>} validatorVotes - 6 validators
* @param {object} [options]
* @param {number} [options.passThreshold=7] - min cyclic-audit passes (out of 9) to commit
* @param {(round:number, validators:Array) => Array} [options.pollFn] - see runCyclicAudit
* @returns {{ok:true, value:{outcome:string, details:object}}|{ok:false, error:VortexVoteError}}
*/
export function middlePath(seedVotes, validatorVotes, options = {}) {
const { passThreshold = 7, pollFn = null } = options;
const seedCheck = validateVoteArray(seedVotes, 3, "seedVotes");
if (isErr(seedCheck)) return seedCheck;
const validatorCheck = validateVoteArray(validatorVotes, 6, "validatorVotes");
if (isErr(validatorCheck)) return validatorCheck;
const seeds = takeFirst(seedCheck.value, 3);
if (!hasQuorum(seeds, 3)) {
return Ok({ outcome: Outcome.ABORT, details: { reason: "no seed quorum" } });
}
const validators = takeFirst(validatorCheck.value, 6);
const audit = runCyclicAudit(validators, 9, pollFn);
if (audit.passes >= passThreshold) {
return Ok({ outcome: Outcome.COMMIT, details: { ...audit, passThreshold } });
}
return Ok({ outcome: Outcome.RECONCILE, details: { ...audit, passThreshold } });
}
// ───────────────────────────────────────────────────────────────────────
// §7 — SLOW PATH: 7-4-?
// 7 discrete vote states, 4 structural gates, '?' = entropy/wait buffer
//
// Check order is the specification (documented explicitly, per the
// whitepaper's GAP 03): structural gates dominate escalation, which
// dominates the entropy buffer, which dominates the plain vote tally.
// Reordering these checks is a behavioral change, not a refactor.
// ───────────────────────────────────────────────────────────────────────
/**
* @param {boolean[]} gateChecks - results of the 4 structural integrity gates
* @returns {boolean}
*/
export function allGatesClear(gateChecks) {
return gateChecks.slice(0, 4).every(Boolean);
}
/**
* @param {string[]} stateVotes - values from VoteState
* @returns {boolean}
*/
export function majorityYes(stateVotes) {
if (!stateVotes.length) return false;
const yes = stateVotes.filter((s) => s === VoteState.YES).length;
return yes > stateVotes.length / 2;
}
/**
* @param {object} params
* @param {string[]} params.stateVotes - one of the 7 VoteState values per agent
* @param {boolean[]} params.gateChecks - 4 structural gate results
* @param {boolean} [params.entropyBufferTriggered=false] - the '?' human-in-loop trigger
* @returns {{ok:true, value:{outcome:string, details:object}}|{ok:false, error:VortexVoteError}}
*/
export function slowPath({ stateVotes, gateChecks, entropyBufferTriggered = false }) {
const gateCheckResult = validateGateArray(gateChecks);
if (isErr(gateCheckResult)) return gateCheckResult;
const stateVoteResult = validateStateVotes(stateVotes);
if (isErr(stateVoteResult)) return stateVoteResult;
if (typeof entropyBufferTriggered !== "boolean") {
return Err(new VortexVoteError(
ErrorCode.INVALID_VOTE_ENTRY,
`entropyBufferTriggered must be a boolean, got ${typeof entropyBufferTriggered}`,
{ received: entropyBufferTriggered }
));
}
// ── ordered guard chain — see comment block above ──
if (!allGatesClear(gateCheckResult.value)) {
return Ok({ outcome: Outcome.HOLD, details: { reason: "structural gates not clear" } });
}
if (stateVoteResult.value.some((s) => s === VoteState.ESCALATE)) {
return Ok({ outcome: Outcome.HUMAN_REVIEW, details: { reason: "escalate vote present" } });
}
if (entropyBufferTriggered) {
return Ok({ outcome: Outcome.DELAY_AND_AUDIT, details: { reason: "entropy buffer triggered ('?')" } });
}
if (majorityYes(stateVoteResult.value)) {
return Ok({ outcome: Outcome.SAFE_COMMIT, details: {} });
}
return Ok({ outcome: Outcome.ABORT, details: { reason: "no majority yes" } });
}
// ───────────────────────────────────────────────────────────────────────
// §8 — runVote() dispatcher
// ───────────────────────────────────────────────────────────────────────
/**
* Dispatches to the appropriate path implementation. An unrecognized
* `path` is a programmer error, not a business outcome — it returns
* Err(VortexVoteError), same as any other validation failure, rather
* than throwing, keeping error handling uniform across the whole module
* instead of mixing exceptions with silent ABORT/HOLD degradation.
*
* @param {string} path - one of VotePath
* @param {object} input - shape depends on path; see fastPath/middlePath/slowPath
* @returns {{ok:true, value:{outcome:string, details:object}}|{ok:false, error:VortexVoteError}}
*/
export function runVote(path, input) {
switch (path) {
case VotePath.FAST:
return fastPath(input.primaryVotes, input.stabilizerVotes);
case VotePath.MIDDLE:
return middlePath(input.seedVotes, input.validatorVotes, {
passThreshold: input.passThreshold,
pollFn: input.pollFn,
});
case VotePath.SLOW:
return slowPath(input);
default:
return Err(new VortexVoteError(
ErrorCode.INVALID_PATH,
`Unknown vote path: ${JSON.stringify(path)}. Expected one of: ${Object.values(VotePath).join(", ")}`,
{ received: path }
));
}
}
export default {
Ok, Err, isOk, isErr, unwrap,
ErrorCode, VortexVoteError,
Outcome, VoteState, VotePath,
fastPath, middlePath, slowPath,
runCyclicAudit, allGatesClear, majorityYes,
runVote,
};
// ───────────────────────────────────────────────────────────────────────
// §9 — Bun demo runner — `bun run vortexVote.js`
// ───────────────────────────────────────────────────────────────────────
if (import.meta.main) {
const accept = () => ({ vote: "accept" });
const reject = () => ({ vote: "reject" });
const report = (label, result) => {
console.log(`\n--- ${label} ---`);
if (isOk(result)) {
console.log(result.value);
} else {
console.log(`ERR [${result.error.code}] ${result.error.message}`);
}
};
report("FAST PATH — legitimate rollback", runVote(VotePath.FAST, {
primaryVotes: [accept(), accept(), accept()],
stabilizerVotes: [accept(), reject(), reject(), reject()],
}));
report("FAST PATH — malformed call (caller bug)", runVote(VotePath.FAST, {
primaryVotes: undefined,
stabilizerVotes: [accept(), accept(), accept(), accept()],
}));
report("MIDDLE PATH — static audit (no pollFn, deterministic 0 or 9)", runVote(VotePath.MIDDLE, {
seedVotes: [accept(), accept(), accept()],
validatorVotes: [accept(), accept(), accept(), accept(), reject(), reject()],
}));
// Demonstrates the GAP-02 fix: a pollFn gives each round independent
// variance, so `passes` can land anywhere in [0,9], not just {0,9}.
let flakyRound = 0;
const flakyPollFn = (round, validators) => {
flakyRound = round;
// simulate one validator being flaky on odd rounds
return validators.map((v, i) =>
i === 0 && round % 2 === 1 ? { vote: "reject" } : v
);
};
report("MIDDLE PATH — live pollFn (genuine per-round independence)", runVote(VotePath.MIDDLE, {
seedVotes: [accept(), accept(), accept()],
validatorVotes: [accept(), accept(), accept(), accept(), reject(), reject()],
pollFn: flakyPollFn,
}));
report("SLOW PATH — safe commit", runVote(VotePath.SLOW, {
stateVotes: [VoteState.YES, VoteState.YES, VoteState.MAYBE],
gateChecks: [true, true, true, true],
entropyBufferTriggered: false,
}));
report("SLOW PATH — invalid state value (caller typo, now caught)", runVote(VotePath.SLOW, {
stateVotes: [VoteState.YES, "yess"],
gateChecks: [true, true, true, true],
entropyBufferTriggered: false,
}));
report("runVote — unknown path", runVote("ludicrous-speed", {}));
}