@ngockhoale/ckit 0.0.0-stage → 0.1.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.
- package/.env.example +42 -0
- package/README.md +116 -2
- package/dist/src/adapters/agent/claude/errors.d.ts +13 -0
- package/dist/src/adapters/agent/claude/errors.js +16 -0
- package/dist/src/adapters/agent/claude/normalize.d.ts +11 -0
- package/dist/src/adapters/agent/claude/normalize.js +83 -0
- package/dist/src/adapters/agent/errors.d.ts +13 -0
- package/dist/src/adapters/agent/errors.js +19 -0
- package/dist/src/adapters/agent/fixtures/claude-transcript.d.ts +70 -0
- package/dist/src/adapters/agent/fixtures/claude-transcript.js +15 -0
- package/dist/src/adapters/agent/fixtures/omp-transcript.d.ts +60 -0
- package/dist/src/adapters/agent/fixtures/omp-transcript.js +14 -0
- package/dist/src/adapters/agent/normalize.d.ts +18 -0
- package/dist/src/adapters/agent/normalize.js +77 -0
- package/dist/src/adapters/agent/transport.d.ts +35 -0
- package/dist/src/adapters/agent/transport.js +39 -0
- package/dist/src/adapters/agent/worker-service.d.ts +49 -0
- package/dist/src/adapters/agent/worker-service.js +77 -0
- package/dist/src/adapters/fake/fake-advisor.d.ts +15 -0
- package/dist/src/adapters/fake/fake-advisor.js +29 -0
- package/dist/src/adapters/fake/fake-agent.d.ts +12 -0
- package/dist/src/adapters/fake/fake-agent.js +21 -0
- package/dist/src/adapters/fake/fake-store.d.ts +13 -0
- package/dist/src/adapters/fake/fake-store.js +23 -0
- package/dist/src/adapters/fake/fake-web.d.ts +12 -0
- package/dist/src/adapters/fake/fake-web.js +21 -0
- package/dist/src/adapters/fake/fault-injector.d.ts +18 -0
- package/dist/src/adapters/fake/fault-injector.js +64 -0
- package/dist/src/adapters/fake/virtual-clock.d.ts +12 -0
- package/dist/src/adapters/fake/virtual-clock.js +35 -0
- package/dist/src/adapters/launch/discover.d.ts +18 -0
- package/dist/src/adapters/launch/discover.js +55 -0
- package/dist/src/adapters/launch/executor.d.ts +117 -0
- package/dist/src/adapters/launch/executor.js +383 -0
- package/dist/src/adapters/launch/profile.d.ts +35 -0
- package/dist/src/adapters/launch/profile.js +73 -0
- package/dist/src/adapters/launch/spawn.d.ts +29 -0
- package/dist/src/adapters/launch/spawn.js +18 -0
- package/dist/src/adapters/openai/openai-advisor.d.ts +56 -0
- package/dist/src/adapters/openai/openai-advisor.js +146 -0
- package/dist/src/cli/ckit.d.ts +5 -0
- package/dist/src/cli/ckit.js +472 -0
- package/dist/src/cli/demo.d.ts +1 -0
- package/dist/src/cli/demo.js +30 -0
- package/dist/src/cli/sessions.d.ts +10 -0
- package/dist/src/cli/sessions.js +381 -0
- package/dist/src/cli/setup.d.ts +11 -0
- package/dist/src/cli/setup.js +115 -0
- package/dist/src/committee/decision.d.ts +84 -0
- package/dist/src/committee/decision.js +167 -0
- package/dist/src/committee/handover.d.ts +115 -0
- package/dist/src/committee/handover.js +191 -0
- package/dist/src/committee/no-progress.d.ts +44 -0
- package/dist/src/committee/no-progress.js +64 -0
- package/dist/src/committee/primary-registry.d.ts +15 -0
- package/dist/src/committee/primary-registry.js +60 -0
- package/dist/src/committee/reply-parser.d.ts +28 -0
- package/dist/src/committee/reply-parser.js +53 -0
- package/dist/src/committee/reviewer-scheduler.d.ts +101 -0
- package/dist/src/committee/reviewer-scheduler.js +163 -0
- package/dist/src/committee/role-epoch.d.ts +91 -0
- package/dist/src/committee/role-epoch.js +154 -0
- package/dist/src/core/control.d.ts +18 -0
- package/dist/src/core/control.js +29 -0
- package/dist/src/core/entities.d.ts +166 -0
- package/dist/src/core/entities.js +119 -0
- package/dist/src/core/errors.d.ts +9 -0
- package/dist/src/core/errors.js +17 -0
- package/dist/src/core/events.d.ts +72 -0
- package/dist/src/core/events.js +125 -0
- package/dist/src/core/ids.d.ts +47 -0
- package/dist/src/core/ids.js +32 -0
- package/dist/src/core/machine.d.ts +55 -0
- package/dist/src/core/machine.js +110 -0
- package/dist/src/core/policy.d.ts +34 -0
- package/dist/src/core/policy.js +59 -0
- package/dist/src/core/provenance.d.ts +20 -0
- package/dist/src/core/provenance.js +21 -0
- package/dist/src/core/record.d.ts +35 -0
- package/dist/src/core/record.js +67 -0
- package/dist/src/core/replay.d.ts +10 -0
- package/dist/src/core/replay.js +36 -0
- package/dist/src/core/run-task.d.ts +20 -0
- package/dist/src/core/run-task.js +48 -0
- package/dist/src/diagnostics/doctor.d.ts +78 -0
- package/dist/src/diagnostics/doctor.js +365 -0
- package/dist/src/diagnostics/journal-lock.d.ts +38 -0
- package/dist/src/diagnostics/journal-lock.js +181 -0
- package/dist/src/evidence/linker.d.ts +44 -0
- package/dist/src/evidence/linker.js +75 -0
- package/dist/src/evidence/report-parser.d.ts +27 -0
- package/dist/src/evidence/report-parser.js +17 -0
- package/dist/src/evidence/store.d.ts +36 -0
- package/dist/src/evidence/store.js +57 -0
- package/dist/src/gui/server.d.ts +27 -0
- package/dist/src/gui/server.js +497 -0
- package/dist/src/host/checkpoint.d.ts +22 -0
- package/dist/src/host/checkpoint.js +74 -0
- package/dist/src/host/export.d.ts +52 -0
- package/dist/src/host/export.js +45 -0
- package/dist/src/host/ipc.d.ts +57 -0
- package/dist/src/host/ipc.js +124 -0
- package/dist/src/host/leases.d.ts +27 -0
- package/dist/src/host/leases.js +40 -0
- package/dist/src/host/retention.d.ts +47 -0
- package/dist/src/host/retention.js +130 -0
- package/dist/src/host/supervisor.d.ts +59 -0
- package/dist/src/host/supervisor.js +64 -0
- package/dist/src/intake/owner-intake.d.ts +31 -0
- package/dist/src/intake/owner-intake.js +97 -0
- package/dist/src/intake/types.d.ts +46 -0
- package/dist/src/intake/types.js +2 -0
- package/dist/src/intent/context-packet.d.ts +68 -0
- package/dist/src/intent/context-packet.js +76 -0
- package/dist/src/intent/idea-ledger.d.ts +50 -0
- package/dist/src/intent/idea-ledger.js +136 -0
- package/dist/src/intent/ledger.d.ts +35 -0
- package/dist/src/intent/ledger.js +40 -0
- package/dist/src/intent/registry.d.ts +51 -0
- package/dist/src/intent/registry.js +44 -0
- package/dist/src/intent/revision.d.ts +37 -0
- package/dist/src/intent/revision.js +48 -0
- package/dist/src/orchestration/dispatcher.d.ts +32 -0
- package/dist/src/orchestration/dispatcher.js +136 -0
- package/dist/src/orchestration/milestone-loop.d.ts +149 -0
- package/dist/src/orchestration/milestone-loop.js +132 -0
- package/dist/src/orchestration/recovery-coordinator.d.ts +74 -0
- package/dist/src/orchestration/recovery-coordinator.js +180 -0
- package/dist/src/orchestration/work-order-contract.d.ts +44 -0
- package/dist/src/orchestration/work-order-contract.js +85 -0
- package/dist/src/orchestration/work-queue.d.ts +56 -0
- package/dist/src/orchestration/work-queue.js +95 -0
- package/dist/src/ports/advisor.d.ts +33 -0
- package/dist/src/ports/advisor.js +2 -0
- package/dist/src/ports/agent.d.ts +31 -0
- package/dist/src/ports/agent.js +2 -0
- package/dist/src/ports/capabilities.d.ts +3 -0
- package/dist/src/ports/capabilities.js +5 -0
- package/dist/src/ports/clock.d.ts +5 -0
- package/dist/src/ports/clock.js +5 -0
- package/dist/src/ports/store.d.ts +13 -0
- package/dist/src/ports/store.js +2 -0
- package/dist/src/ports/web.d.ts +29 -0
- package/dist/src/ports/web.js +2 -0
- package/dist/src/run/api-run.d.ts +49 -0
- package/dist/src/run/api-run.js +173 -0
- package/dist/src/run/plan-run.d.ts +22 -0
- package/dist/src/run/plan-run.js +233 -0
- package/dist/src/run/plan.d.ts +36 -0
- package/dist/src/run/plan.js +119 -0
- package/dist/src/run/verify.d.ts +25 -0
- package/dist/src/run/verify.js +81 -0
- package/dist/src/security/redact.d.ts +7 -0
- package/dist/src/security/redact.js +21 -0
- package/dist/src/settings/env-config.d.ts +64 -0
- package/dist/src/settings/env-config.js +232 -0
- package/dist/src/storage/artifacts.d.ts +30 -0
- package/dist/src/storage/artifacts.js +105 -0
- package/dist/src/storage/audit.d.ts +6 -0
- package/dist/src/storage/audit.js +6 -0
- package/dist/src/storage/db.d.ts +9 -0
- package/dist/src/storage/db.js +43 -0
- package/dist/src/storage/events.d.ts +20 -0
- package/dist/src/storage/events.js +69 -0
- package/dist/src/storage/migrations.d.ts +8 -0
- package/dist/src/storage/migrations.js +48 -0
- package/dist/src/storage/outbox.d.ts +25 -0
- package/dist/src/storage/outbox.js +40 -0
- package/dist/src/storage/projections.d.ts +18 -0
- package/dist/src/storage/projections.js +40 -0
- package/dist/src/storage/reconcile.d.ts +14 -0
- package/dist/src/storage/reconcile.js +93 -0
- package/dist/src/storage/reservations.d.ts +12 -0
- package/dist/src/storage/reservations.js +80 -0
- package/dist/src/storage/store.d.ts +34 -0
- package/dist/src/storage/store.js +105 -0
- package/dist/src/team/attachments.d.ts +22 -0
- package/dist/src/team/attachments.js +211 -0
- package/dist/src/team/cli-models.d.ts +24 -0
- package/dist/src/team/cli-models.js +72 -0
- package/dist/src/team/config.d.ts +20 -0
- package/dist/src/team/config.js +111 -0
- package/dist/src/team/engine.d.ts +28 -0
- package/dist/src/team/engine.js +443 -0
- package/dist/src/team/journal.d.ts +30 -0
- package/dist/src/team/journal.js +70 -0
- package/dist/src/team/runners.d.ts +79 -0
- package/dist/src/team/runners.js +436 -0
- package/dist/src/team/secrets.d.ts +10 -0
- package/dist/src/team/secrets.js +68 -0
- package/dist/src/team/types.d.ts +155 -0
- package/dist/src/team/types.js +5 -0
- package/dist/src/tui/app.d.ts +29 -0
- package/dist/src/tui/app.js +96 -0
- package/dist/src/tui/control-model.d.ts +101 -0
- package/dist/src/tui/control-model.js +109 -0
- package/dist/src/tui/control-screens.d.ts +27 -0
- package/dist/src/tui/control-screens.js +85 -0
- package/dist/src/tui/graph-model.d.ts +34 -0
- package/dist/src/tui/graph-model.js +29 -0
- package/dist/src/tui/graph-screens.d.ts +13 -0
- package/dist/src/tui/graph-screens.js +4 -0
- package/dist/src/tui/inspector-model.d.ts +150 -0
- package/dist/src/tui/inspector-model.js +15 -0
- package/dist/src/tui/inspector-screens.d.ts +14 -0
- package/dist/src/tui/inspector-screens.js +61 -0
- package/dist/src/tui/live.d.ts +16 -0
- package/dist/src/tui/live.js +39 -0
- package/dist/src/tui/mission-action-screens.d.ts +15 -0
- package/dist/src/tui/mission-action-screens.js +105 -0
- package/dist/src/tui/mission-actions.d.ts +46 -0
- package/dist/src/tui/mission-actions.js +53 -0
- package/dist/src/tui/mission-model.d.ts +120 -0
- package/dist/src/tui/mission-model.js +164 -0
- package/dist/src/tui/mission-nav.d.ts +82 -0
- package/dist/src/tui/mission-nav.js +131 -0
- package/dist/src/tui/mission-plan-screens.d.ts +11 -0
- package/dist/src/tui/mission-plan-screens.js +40 -0
- package/dist/src/tui/mission-plan.d.ts +45 -0
- package/dist/src/tui/mission-plan.js +166 -0
- package/dist/src/tui/mission-screens.d.ts +7 -0
- package/dist/src/tui/mission-screens.js +263 -0
- package/dist/src/tui/provenance-label.d.ts +11 -0
- package/dist/src/tui/provenance-label.js +16 -0
- package/dist/src/tui/screens.d.ts +10 -0
- package/dist/src/tui/screens.js +34 -0
- package/dist/src/tui/session-outcome.d.ts +14 -0
- package/dist/src/tui/session-outcome.js +57 -0
- package/dist/src/tui/setup-model.d.ts +159 -0
- package/dist/src/tui/setup-model.js +234 -0
- package/dist/src/tui/setup-screens.d.ts +66 -0
- package/dist/src/tui/setup-screens.js +72 -0
- package/dist/src/tui/team/app.d.ts +24 -0
- package/dist/src/tui/team/app.js +228 -0
- package/dist/src/tui/team/demo-handle.d.ts +22 -0
- package/dist/src/tui/team/demo-handle.js +42 -0
- package/dist/src/tui/team/model.d.ts +81 -0
- package/dist/src/tui/team/model.js +133 -0
- package/gui/app.css +177 -0
- package/gui/app.js +675 -0
- package/gui/index.html +51 -0
- package/gui/network.js +413 -0
- package/package.json +45 -4
- package/src/storage/schema.sql +42 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { advisorId } from '../core/ids.js';
|
|
2
|
+
/** In-memory registry of bound advisors and their deterministic failover order. */
|
|
3
|
+
export class PrimaryRegistry {
|
|
4
|
+
registered = new Map();
|
|
5
|
+
orderedFallbacks = [];
|
|
6
|
+
selected = null;
|
|
7
|
+
get bindings() { return Object.freeze([...this.registered.values()]); }
|
|
8
|
+
get primary() { return this.selected === null ? undefined : this.registered.get(this.selected); }
|
|
9
|
+
get fallbackOrder() { return Object.freeze([...this.orderedFallbacks]); }
|
|
10
|
+
register(binding) {
|
|
11
|
+
if (!binding || typeof binding !== 'object')
|
|
12
|
+
throw new TypeError('advisor binding required');
|
|
13
|
+
const id = advisorId(binding.advisorId);
|
|
14
|
+
if (typeof binding.provider !== 'string' || !binding.provider.trim() || typeof binding.url !== 'string' || !binding.url.trim() || typeof binding.profileRef !== 'string' || !binding.profileRef.trim() || !Array.isArray(binding.capabilities))
|
|
15
|
+
throw new TypeError('valid advisor binding required');
|
|
16
|
+
if (binding.conversationId !== null && (typeof binding.conversationId !== 'string' || !binding.conversationId.trim()))
|
|
17
|
+
throw new TypeError('valid conversation binding required');
|
|
18
|
+
if (this.registered.has(id))
|
|
19
|
+
throw new TypeError('advisor binding IDs are unique');
|
|
20
|
+
if (binding.role === 'reviewer')
|
|
21
|
+
throw new TypeError('reviewer bindings cannot be registered as primary or fallback advisors');
|
|
22
|
+
const isFirst = this.selected === null;
|
|
23
|
+
const copy = Object.freeze({ ...binding, role: isFirst ? 'primary' : 'fallback', capabilities: Object.freeze([...binding.capabilities]) });
|
|
24
|
+
this.registered.set(id, copy);
|
|
25
|
+
if (isFirst)
|
|
26
|
+
this.selected = id; // A single advisor binding is auto-primary.
|
|
27
|
+
return copy;
|
|
28
|
+
}
|
|
29
|
+
selectPrimary(rawId) {
|
|
30
|
+
const id = advisorId(rawId);
|
|
31
|
+
const target = this.registered.get(id);
|
|
32
|
+
if (!target)
|
|
33
|
+
throw new TypeError('primary must reference a registered advisor binding');
|
|
34
|
+
for (const [candidate, binding] of this.registered) {
|
|
35
|
+
this.registered.set(candidate, Object.freeze({ ...binding, role: candidate === id ? 'primary' : 'fallback' }));
|
|
36
|
+
}
|
|
37
|
+
this.selected = id;
|
|
38
|
+
this.orderedFallbacks = this.orderedFallbacks.filter((candidate) => candidate !== id);
|
|
39
|
+
return this.registered.get(id);
|
|
40
|
+
}
|
|
41
|
+
setFallbackOrder(rawIds) {
|
|
42
|
+
if (!Array.isArray(rawIds))
|
|
43
|
+
throw new TypeError('fallback order must be an array');
|
|
44
|
+
const ids = rawIds.map(advisorId);
|
|
45
|
+
if (new Set(ids).size !== ids.length)
|
|
46
|
+
throw new TypeError('fallback advisor IDs must be unique');
|
|
47
|
+
if (this.selected !== null && ids.includes(this.selected))
|
|
48
|
+
throw new TypeError('primary cannot also be a fallback');
|
|
49
|
+
for (const id of ids)
|
|
50
|
+
if (!this.registered.has(id))
|
|
51
|
+
throw new TypeError('fallback must reference a registered advisor binding');
|
|
52
|
+
this.orderedFallbacks = ids;
|
|
53
|
+
return Object.freeze(ids.map((id) => this.registered.get(id)));
|
|
54
|
+
}
|
|
55
|
+
nextFallback() {
|
|
56
|
+
const id = this.orderedFallbacks[0];
|
|
57
|
+
return id === undefined ? undefined : this.registered.get(id);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=primary-registry.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export type CommitteeReply = {
|
|
2
|
+
readonly kind: 'final';
|
|
3
|
+
readonly outcome: 'execute' | 'investigate' | 'needs_owner' | 'done' | 'reject';
|
|
4
|
+
readonly rationale: string;
|
|
5
|
+
readonly evidenceRefs: readonly string[];
|
|
6
|
+
} | {
|
|
7
|
+
readonly kind: 'review-request';
|
|
8
|
+
readonly reason: string;
|
|
9
|
+
readonly reviewers: readonly string[];
|
|
10
|
+
};
|
|
11
|
+
export interface ReplyAuditEntry {
|
|
12
|
+
readonly kind: 'reply-accepted' | 'reply-rejected' | 'deterministic-fix';
|
|
13
|
+
readonly reason: string;
|
|
14
|
+
}
|
|
15
|
+
export type ParsedCommitteeReply = {
|
|
16
|
+
readonly kind: 'accepted';
|
|
17
|
+
readonly reply: CommitteeReply;
|
|
18
|
+
} | {
|
|
19
|
+
readonly kind: 'rejected';
|
|
20
|
+
readonly reason: string;
|
|
21
|
+
readonly deterministicFix: 'strip_fence_and_validate' | 'none';
|
|
22
|
+
readonly modelRepairAllowed: boolean;
|
|
23
|
+
readonly slotsRemaining: number;
|
|
24
|
+
};
|
|
25
|
+
export declare function parseCommitteeReply(raw: unknown, options?: {
|
|
26
|
+
readonly audit?: ReplyAuditEntry[];
|
|
27
|
+
readonly slotsRemaining?: number;
|
|
28
|
+
}): ParsedCommitteeReply;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export function parseCommitteeReply(raw, options = {}) {
|
|
2
|
+
const slots = options.slotsRemaining ?? 2;
|
|
3
|
+
if (!Number.isSafeInteger(slots) || slots < 0 || slots > 2)
|
|
4
|
+
throw new TypeError('slotsRemaining must be an integer from zero to two');
|
|
5
|
+
let value = raw;
|
|
6
|
+
let fixed = false;
|
|
7
|
+
if (typeof value === 'string') {
|
|
8
|
+
const text = value;
|
|
9
|
+
try {
|
|
10
|
+
value = JSON.parse(text);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
const stripped = text.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
|
|
14
|
+
if (/^```(?:json)?\s*/i.test(text.trim()) && /\s*```$/.test(text.trim())) {
|
|
15
|
+
try {
|
|
16
|
+
value = JSON.parse(stripped);
|
|
17
|
+
fixed = true;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return reject('malformed JSON', fixed, slots, options.audit);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
else
|
|
24
|
+
return reject('malformed JSON', false, slots, options.audit);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (!isRecord(value))
|
|
28
|
+
return reject('reply must be an object', fixed, slots, options.audit);
|
|
29
|
+
if ('control' in value)
|
|
30
|
+
return reject('mismatched control block', fixed, slots, options.audit);
|
|
31
|
+
if (value['kind'] === 'final' && isOutcome(value['outcome']) && nonEmpty(value['rationale']) && Array.isArray(value['evidenceRefs']) && value['evidenceRefs'].every(nonEmpty)) {
|
|
32
|
+
const reply = Object.freeze({ kind: 'final', outcome: value['outcome'], rationale: value['rationale'], evidenceRefs: Object.freeze([...value['evidenceRefs']]) });
|
|
33
|
+
options.audit?.push(Object.freeze({ kind: fixed ? 'deterministic-fix' : 'reply-accepted', reason: fixed ? 'stripped JSON fence' : 'valid final reply' }));
|
|
34
|
+
return Object.freeze({ kind: 'accepted', reply });
|
|
35
|
+
}
|
|
36
|
+
if (value['kind'] === 'review-request' && nonEmpty(value['reason']) && Array.isArray(value['reviewers']) && value['reviewers'].length > 0 && value['reviewers'].every(nonEmpty)) {
|
|
37
|
+
const reply = Object.freeze({ kind: 'review-request', reason: value['reason'], reviewers: Object.freeze([...value['reviewers']]) });
|
|
38
|
+
options.audit?.push(Object.freeze({ kind: fixed ? 'deterministic-fix' : 'reply-accepted', reason: fixed ? 'stripped JSON fence' : 'valid reviewer request' }));
|
|
39
|
+
return Object.freeze({ kind: 'accepted', reply });
|
|
40
|
+
}
|
|
41
|
+
return reject('invalid reply schema', fixed, slots, options.audit);
|
|
42
|
+
}
|
|
43
|
+
function reject(reason, fixed, slots, audit) {
|
|
44
|
+
audit?.push(Object.freeze({ kind: 'reply-rejected', reason }));
|
|
45
|
+
if (fixed)
|
|
46
|
+
audit?.push(Object.freeze({ kind: 'deterministic-fix', reason: 'attempted fence removal' }));
|
|
47
|
+
const remaining = Math.max(0, slots - (fixed ? 1 : 0));
|
|
48
|
+
return Object.freeze({ kind: 'rejected', reason, deterministicFix: fixed ? 'strip_fence_and_validate' : 'none', modelRepairAllowed: remaining > 0, slotsRemaining: remaining });
|
|
49
|
+
}
|
|
50
|
+
function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
|
|
51
|
+
function nonEmpty(value) { return typeof value === 'string' && value.trim().length > 0; }
|
|
52
|
+
function isOutcome(value) { return value === 'execute' || value === 'investigate' || value === 'needs_owner' || value === 'done' || value === 'reject'; }
|
|
53
|
+
//# sourceMappingURL=reply-parser.js.map
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import type { PrimaryContextPacket } from '../intent/context-packet.js';
|
|
2
|
+
import { type DecisionAudit } from './decision.js';
|
|
3
|
+
import type { RoleEpoch, WorkOrderState } from './role-epoch.js';
|
|
4
|
+
export interface ReviewerSnapshot {
|
|
5
|
+
readonly decisionId: string;
|
|
6
|
+
readonly evidenceRevision: number;
|
|
7
|
+
readonly packet: PrimaryContextPacket;
|
|
8
|
+
readonly revision: number;
|
|
9
|
+
}
|
|
10
|
+
export interface ScheduledReviewer {
|
|
11
|
+
readonly requestId: string;
|
|
12
|
+
readonly reviewerId: string;
|
|
13
|
+
readonly reason: string;
|
|
14
|
+
readonly snapshot: ReviewerSnapshot;
|
|
15
|
+
readonly status: 'pending' | 'submitted' | 'timed_out';
|
|
16
|
+
readonly opinion?: unknown;
|
|
17
|
+
readonly deadline?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface ReviewerAudit extends DecisionAudit {
|
|
20
|
+
readonly evidenceRevision?: number;
|
|
21
|
+
readonly reviewerIds?: readonly string[];
|
|
22
|
+
readonly late?: boolean;
|
|
23
|
+
}
|
|
24
|
+
export interface ReviewerSchedulerOptions {
|
|
25
|
+
readonly decisionId: string;
|
|
26
|
+
readonly primaryId: string;
|
|
27
|
+
readonly evidenceRevision: number;
|
|
28
|
+
readonly snapshot: PrimaryContextPacket;
|
|
29
|
+
readonly maxReviewersPerAdvisor?: number;
|
|
30
|
+
readonly reviewerCap?: number;
|
|
31
|
+
readonly acknowledgementCalls?: number;
|
|
32
|
+
}
|
|
33
|
+
export interface ReviewerRequest {
|
|
34
|
+
readonly reason: string;
|
|
35
|
+
readonly reviewers: readonly string[];
|
|
36
|
+
readonly deadline?: number;
|
|
37
|
+
}
|
|
38
|
+
export interface FinalDecision {
|
|
39
|
+
readonly outcome: string;
|
|
40
|
+
readonly rationale: string;
|
|
41
|
+
}
|
|
42
|
+
export interface SchedulerAccounting {
|
|
43
|
+
readonly primaryCalls: number;
|
|
44
|
+
readonly acknowledgementCalls: number;
|
|
45
|
+
readonly workOrders: number;
|
|
46
|
+
readonly reviewerCalls: Readonly<Record<string, number>>;
|
|
47
|
+
}
|
|
48
|
+
/** Model-free, in-memory accounting and snapshot-bound reviewer selection policy. */
|
|
49
|
+
export declare class ReviewerScheduler {
|
|
50
|
+
private readonly engine;
|
|
51
|
+
private readonly evidenceRevision;
|
|
52
|
+
private readonly snapshot;
|
|
53
|
+
private readonly cap;
|
|
54
|
+
private readonly reviewerCap;
|
|
55
|
+
private readonly reviewerCount;
|
|
56
|
+
private reviewers;
|
|
57
|
+
private auditEntries;
|
|
58
|
+
private finalized;
|
|
59
|
+
private synthesized;
|
|
60
|
+
private reviewerRequested;
|
|
61
|
+
private readonly late;
|
|
62
|
+
private order;
|
|
63
|
+
private started;
|
|
64
|
+
private nextPrimary;
|
|
65
|
+
private readonly ackCalls;
|
|
66
|
+
constructor(options: ReviewerSchedulerOptions);
|
|
67
|
+
startPrimary(): {
|
|
68
|
+
readonly requestId: string;
|
|
69
|
+
readonly advisorId: string;
|
|
70
|
+
readonly purpose: 'bootstrap' | 'continue';
|
|
71
|
+
};
|
|
72
|
+
requestReviewers(primaryRequestId: string, request: ReviewerRequest): readonly ScheduledReviewer[];
|
|
73
|
+
private assertReviewerCapacity;
|
|
74
|
+
finalize(primaryRequestId: string, decision: FinalDecision): FinalDecision;
|
|
75
|
+
submitOpinion(requestId: string, opinion: unknown, options?: {
|
|
76
|
+
readonly at?: number;
|
|
77
|
+
}): 'accepted' | 'late';
|
|
78
|
+
timeoutReviewer(requestId: string): void;
|
|
79
|
+
synthesize(): {
|
|
80
|
+
readonly decision: FinalDecision | null;
|
|
81
|
+
readonly opinions: readonly {
|
|
82
|
+
readonly reviewerId: string;
|
|
83
|
+
readonly opinion: unknown;
|
|
84
|
+
}[];
|
|
85
|
+
};
|
|
86
|
+
opinionVisibility(requestId: string): readonly unknown[];
|
|
87
|
+
acceptWorkOrder(roleEpoch: RoleEpoch, workOrderId: string, state: {
|
|
88
|
+
readonly checkpoint: unknown;
|
|
89
|
+
readonly state: string;
|
|
90
|
+
}): WorkOrderState;
|
|
91
|
+
get accounting(): SchedulerAccounting;
|
|
92
|
+
get dispatchedReviewers(): readonly ScheduledReviewer[];
|
|
93
|
+
get audit(): readonly ReviewerAudit[];
|
|
94
|
+
get finalDecision(): FinalDecision | null;
|
|
95
|
+
get lateResponses(): readonly {
|
|
96
|
+
readonly requestId: string;
|
|
97
|
+
readonly reviewerId: string;
|
|
98
|
+
readonly at: number;
|
|
99
|
+
readonly opinion: unknown;
|
|
100
|
+
}[];
|
|
101
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { advisorId } from '../core/ids.js';
|
|
2
|
+
import { DecisionEngine } from './decision.js';
|
|
3
|
+
/** Model-free, in-memory accounting and snapshot-bound reviewer selection policy. */
|
|
4
|
+
export class ReviewerScheduler {
|
|
5
|
+
engine;
|
|
6
|
+
evidenceRevision;
|
|
7
|
+
snapshot;
|
|
8
|
+
cap;
|
|
9
|
+
reviewerCap;
|
|
10
|
+
reviewerCount = new Map();
|
|
11
|
+
reviewers = [];
|
|
12
|
+
auditEntries = [];
|
|
13
|
+
finalized = null;
|
|
14
|
+
synthesized = false;
|
|
15
|
+
reviewerRequested = false;
|
|
16
|
+
late = [];
|
|
17
|
+
order = null;
|
|
18
|
+
started = new Set();
|
|
19
|
+
nextPrimary = 1;
|
|
20
|
+
ackCalls;
|
|
21
|
+
constructor(options) {
|
|
22
|
+
if (!options || typeof options.decisionId !== 'string' || !options.decisionId.trim() || typeof options.primaryId !== 'string' || !options.primaryId.trim())
|
|
23
|
+
throw new TypeError('decision and primary IDs required');
|
|
24
|
+
if (!Number.isSafeInteger(options.evidenceRevision) || options.evidenceRevision < 1)
|
|
25
|
+
throw new TypeError('positive evidence revision required');
|
|
26
|
+
if (!options.snapshot || options.snapshot.kind !== 'primary')
|
|
27
|
+
throw new TypeError('primary context snapshot required');
|
|
28
|
+
this.cap = options.reviewerCap ?? 2;
|
|
29
|
+
if (!Number.isSafeInteger(this.cap) || this.cap < 1 || this.cap > 2)
|
|
30
|
+
throw new TypeError('reviewer scheduler primary cap must be one or two');
|
|
31
|
+
this.reviewerCap = options.maxReviewersPerAdvisor ?? 1;
|
|
32
|
+
if (!Number.isSafeInteger(this.reviewerCap) || this.reviewerCap < 1)
|
|
33
|
+
throw new TypeError('positive per-reviewer cap required');
|
|
34
|
+
this.ackCalls = options.acknowledgementCalls ?? 0;
|
|
35
|
+
if (this.ackCalls !== 0)
|
|
36
|
+
throw new TypeError('scheduler does not dispatch acknowledgement calls');
|
|
37
|
+
this.evidenceRevision = options.evidenceRevision;
|
|
38
|
+
this.snapshot = Object.freeze({ decisionId: options.decisionId, evidenceRevision: options.evidenceRevision, packet: options.snapshot, revision: 1 });
|
|
39
|
+
this.engine = new DecisionEngine({ decisionId: options.decisionId, primaryId: options.primaryId, loopLimit: this.cap });
|
|
40
|
+
}
|
|
41
|
+
startPrimary() {
|
|
42
|
+
if (this.finalized !== null)
|
|
43
|
+
throw new Error('decision is terminal');
|
|
44
|
+
if (this.started.size >= this.cap)
|
|
45
|
+
throw new Error('primary call cap exhausted');
|
|
46
|
+
const requestId = `primary-${this.engine.snapshot().decisionId}-${this.nextPrimary++}`;
|
|
47
|
+
const call = this.engine.reservePrimary(requestId, this.started.size === 0 ? 'bootstrap' : 'continue');
|
|
48
|
+
this.engine.settlePrimary(call.requestId, 'sent');
|
|
49
|
+
this.started.add(call.requestId);
|
|
50
|
+
this.auditEntries.push(Object.freeze({ kind: 'primary-call', requestId: call.requestId }));
|
|
51
|
+
return Object.freeze({ requestId: call.requestId, advisorId: call.advisorId, purpose: call.purpose });
|
|
52
|
+
}
|
|
53
|
+
requestReviewers(primaryRequestId, request) {
|
|
54
|
+
if (this.finalized !== null)
|
|
55
|
+
throw new Error('decision is terminal');
|
|
56
|
+
if (!this.started.has(primaryRequestId))
|
|
57
|
+
throw new TypeError('unknown primary request');
|
|
58
|
+
if (this.reviewerRequested)
|
|
59
|
+
throw new Error('reviewer request cap exhausted');
|
|
60
|
+
if (!request || typeof request.reason !== 'string' || !request.reason.trim() || !Array.isArray(request.reviewers) || request.reviewers.length === 0)
|
|
61
|
+
throw new TypeError('review rationale and reviewers required');
|
|
62
|
+
if (request.deadline !== undefined && (!Number.isFinite(request.deadline) || request.deadline < 0))
|
|
63
|
+
throw new TypeError('valid reviewer deadline required');
|
|
64
|
+
const ids = request.reviewers.map((id) => advisorId(id));
|
|
65
|
+
if (new Set(ids).size !== ids.length)
|
|
66
|
+
throw new TypeError('reviewer IDs must be unique per selection');
|
|
67
|
+
this.assertReviewerCapacity(ids);
|
|
68
|
+
const decision = this.engine.finishPrimary(primaryRequestId, { kind: 'review-request', reason: request.reason, reviewers: ids });
|
|
69
|
+
if (decision.outcome !== 'review_requested')
|
|
70
|
+
throw new Error('primary call cap exhausted before review selection');
|
|
71
|
+
const calls = this.engine.reserveReviewers(ids, this.evidenceRevision);
|
|
72
|
+
const selected = calls.map((call) => {
|
|
73
|
+
const count = this.reviewerCount.get(call.reviewerId) ?? 0;
|
|
74
|
+
this.reviewerCount.set(call.reviewerId, count + 1);
|
|
75
|
+
const item = Object.freeze({ requestId: call.requestId, reviewerId: call.reviewerId, reason: request.reason, snapshot: this.snapshot, status: 'pending', ...(request.deadline === undefined ? {} : { deadline: request.deadline }) });
|
|
76
|
+
this.reviewers.push(item);
|
|
77
|
+
return item;
|
|
78
|
+
});
|
|
79
|
+
this.reviewerRequested = true;
|
|
80
|
+
this.auditEntries.push(Object.freeze({ kind: 'review-request', requestId: primaryRequestId, reason: request.reason, evidenceRevision: this.evidenceRevision, reviewerIds: Object.freeze([...ids]) }));
|
|
81
|
+
return Object.freeze(selected);
|
|
82
|
+
}
|
|
83
|
+
assertReviewerCapacity(ids) {
|
|
84
|
+
const attemptedCounts = new Map();
|
|
85
|
+
for (const id of ids) {
|
|
86
|
+
const count = (this.reviewerCount.get(id) ?? 0) + (attemptedCounts.get(id) ?? 0);
|
|
87
|
+
if (count >= this.reviewerCap)
|
|
88
|
+
throw new Error(`reviewer cap exhausted for ${id}`);
|
|
89
|
+
attemptedCounts.set(id, (attemptedCounts.get(id) ?? 0) + 1);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
finalize(primaryRequestId, decision) {
|
|
93
|
+
if (this.finalized !== null)
|
|
94
|
+
throw new Error('decision is already final');
|
|
95
|
+
if (!this.started.has(primaryRequestId))
|
|
96
|
+
throw new TypeError('unknown primary request');
|
|
97
|
+
if (!decision || typeof decision.outcome !== 'string' || !decision.outcome.trim() || typeof decision.rationale !== 'string' || !decision.rationale.trim())
|
|
98
|
+
throw new TypeError('final outcome and rationale required');
|
|
99
|
+
this.engine.finishPrimary(primaryRequestId, { kind: 'final', outcome: decision.outcome, rationale: decision.rationale });
|
|
100
|
+
this.finalized = Object.freeze({ ...decision });
|
|
101
|
+
this.auditEntries.push(Object.freeze({ kind: 'primary-final', requestId: primaryRequestId, reason: decision.rationale }));
|
|
102
|
+
return this.finalized;
|
|
103
|
+
}
|
|
104
|
+
submitOpinion(requestId, opinion, options = {}) {
|
|
105
|
+
const index = this.reviewers.findIndex((x) => x.requestId === requestId);
|
|
106
|
+
if (index < 0)
|
|
107
|
+
throw new TypeError('unknown reviewer request');
|
|
108
|
+
const current = this.reviewers[index];
|
|
109
|
+
const at = options.at ?? Date.now();
|
|
110
|
+
if (!Number.isFinite(at))
|
|
111
|
+
throw new TypeError('valid reply timestamp required');
|
|
112
|
+
const isLate = this.finalized !== null || current.status === 'timed_out' || current.deadline !== undefined && at > current.deadline;
|
|
113
|
+
if (isLate) {
|
|
114
|
+
this.late.push(Object.freeze({ requestId, reviewerId: current.reviewerId, at, opinion: structuredClone(opinion) }));
|
|
115
|
+
this.engine.submitReviewerOpinion(requestId, opinion);
|
|
116
|
+
this.auditEntries.push(Object.freeze({ kind: 'late-review', requestId, reason: 'late response ignored', evidenceRevision: this.evidenceRevision, late: true }));
|
|
117
|
+
return 'late';
|
|
118
|
+
}
|
|
119
|
+
this.engine.submitReviewerOpinion(requestId, opinion);
|
|
120
|
+
this.reviewers[index] = Object.freeze({ ...current, status: 'submitted', opinion: structuredClone(opinion) });
|
|
121
|
+
return 'accepted';
|
|
122
|
+
}
|
|
123
|
+
timeoutReviewer(requestId) {
|
|
124
|
+
const index = this.reviewers.findIndex((x) => x.requestId === requestId);
|
|
125
|
+
if (index < 0 || this.reviewers[index].status !== 'pending')
|
|
126
|
+
throw new TypeError('reviewer is not pending');
|
|
127
|
+
this.engine.timeoutReviewer(requestId);
|
|
128
|
+
this.reviewers[index] = Object.freeze({ ...this.reviewers[index], status: 'timed_out' });
|
|
129
|
+
}
|
|
130
|
+
synthesize() {
|
|
131
|
+
if (this.reviewers.some((x) => x.status === 'pending'))
|
|
132
|
+
throw new Error('all reviewer calls must settle before synthesis');
|
|
133
|
+
this.engine.synthesizeReviewers();
|
|
134
|
+
this.synthesized = true;
|
|
135
|
+
return Object.freeze({ decision: this.finalized, opinions: Object.freeze(this.reviewers.filter((x) => x.status === 'submitted').map((x) => Object.freeze({ reviewerId: x.reviewerId, opinion: structuredClone(x.opinion) }))) });
|
|
136
|
+
}
|
|
137
|
+
opinionVisibility(requestId) {
|
|
138
|
+
if (!this.reviewers.some((x) => x.requestId === requestId))
|
|
139
|
+
throw new TypeError('unknown reviewer request');
|
|
140
|
+
return Object.freeze(this.synthesized ? this.reviewers.filter((x) => x.status === 'submitted').map((x) => structuredClone(x.opinion)) : []);
|
|
141
|
+
}
|
|
142
|
+
acceptWorkOrder(roleEpoch, workOrderId, state) {
|
|
143
|
+
if (this.finalized === null)
|
|
144
|
+
throw new Error('final decision required before work order');
|
|
145
|
+
if (this.finalized.outcome !== 'execute')
|
|
146
|
+
throw new Error('final decision does not authorize work order');
|
|
147
|
+
if (this.order !== null)
|
|
148
|
+
throw new Error('only one work order may be dispatched');
|
|
149
|
+
this.order = roleEpoch.acceptWorkOrder(workOrderId, state);
|
|
150
|
+
return this.order;
|
|
151
|
+
}
|
|
152
|
+
get accounting() {
|
|
153
|
+
const reviewerCalls = {};
|
|
154
|
+
for (const [id, count] of this.reviewerCount)
|
|
155
|
+
reviewerCalls[id] = count;
|
|
156
|
+
return Object.freeze({ primaryCalls: this.started.size, acknowledgementCalls: this.ackCalls, workOrders: this.order === null ? 0 : 1, reviewerCalls: Object.freeze(reviewerCalls) });
|
|
157
|
+
}
|
|
158
|
+
get dispatchedReviewers() { return Object.freeze(this.reviewers.map((review) => Object.freeze({ ...review, snapshot: this.snapshot, opinion: review.opinion === undefined ? undefined : structuredClone(review.opinion) }))); }
|
|
159
|
+
get audit() { return Object.freeze(this.auditEntries.map((entry) => Object.freeze({ ...entry, ...(entry.reviewerIds === undefined ? {} : { reviewerIds: Object.freeze([...entry.reviewerIds]) }) }))); }
|
|
160
|
+
get finalDecision() { return this.finalized === null ? null : Object.freeze({ ...this.finalized }); }
|
|
161
|
+
get lateResponses() { return Object.freeze(this.late.map((record) => Object.freeze({ ...record, opinion: structuredClone(record.opinion) }))); }
|
|
162
|
+
}
|
|
163
|
+
//# sourceMappingURL=reviewer-scheduler.js.map
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { type AdvisorId } from '../core/ids.js';
|
|
2
|
+
import { PrimaryRegistry } from './primary-registry.js';
|
|
3
|
+
export interface PrimaryEpoch {
|
|
4
|
+
readonly epoch: number;
|
|
5
|
+
readonly primaryId: AdvisorId;
|
|
6
|
+
readonly active: boolean;
|
|
7
|
+
readonly changedAt: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ResponseClassification<T = unknown> {
|
|
10
|
+
readonly classification: 'current' | 'stale';
|
|
11
|
+
readonly historyRecorded: boolean;
|
|
12
|
+
readonly dispatched: false;
|
|
13
|
+
readonly value?: T;
|
|
14
|
+
}
|
|
15
|
+
export interface WorkHandover {
|
|
16
|
+
readonly workOrderId: string;
|
|
17
|
+
readonly checkpoint: unknown;
|
|
18
|
+
readonly state: string;
|
|
19
|
+
readonly dispatchCount: 1;
|
|
20
|
+
}
|
|
21
|
+
export interface WorkOrderState extends WorkHandover {
|
|
22
|
+
}
|
|
23
|
+
export type RoleEpochEvent = {
|
|
24
|
+
readonly kind: 'role-switched';
|
|
25
|
+
readonly from: AdvisorId | null;
|
|
26
|
+
readonly to: AdvisorId;
|
|
27
|
+
readonly epoch: number;
|
|
28
|
+
} | {
|
|
29
|
+
readonly kind: 'response-recorded';
|
|
30
|
+
readonly epoch: number;
|
|
31
|
+
readonly classification: 'current' | 'stale';
|
|
32
|
+
} | {
|
|
33
|
+
readonly kind: 'work-order-accepted';
|
|
34
|
+
readonly workOrderId: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* In-memory primary budget and accepted-work state, scoped to this RoleEpoch instance and decision.
|
|
38
|
+
* A restart creates a fresh instance; this is not a persisted ledger and makes no restart-persistence claim.
|
|
39
|
+
* HandoverService.epoch and RoleEpoch.activeEpoch.epoch are separate counters and may diverge on failover.
|
|
40
|
+
* HandoverService owns the live authority fence.
|
|
41
|
+
*/
|
|
42
|
+
export declare class RoleEpoch {
|
|
43
|
+
private epochHistory;
|
|
44
|
+
private responseHistory;
|
|
45
|
+
private eventHistory;
|
|
46
|
+
private consumedRequests;
|
|
47
|
+
private orders;
|
|
48
|
+
private slotStates;
|
|
49
|
+
private handedOver;
|
|
50
|
+
private readonly decision;
|
|
51
|
+
private readonly registry;
|
|
52
|
+
constructor(primaryId: string, options?: {
|
|
53
|
+
readonly decisionId?: string;
|
|
54
|
+
readonly registry?: PrimaryRegistry;
|
|
55
|
+
});
|
|
56
|
+
get activeEpoch(): PrimaryEpoch;
|
|
57
|
+
get epochs(): readonly PrimaryEpoch[];
|
|
58
|
+
get history(): readonly {
|
|
59
|
+
readonly epoch: number;
|
|
60
|
+
readonly value: unknown;
|
|
61
|
+
readonly classification: 'current' | 'stale';
|
|
62
|
+
}[];
|
|
63
|
+
get events(): readonly RoleEpochEvent[];
|
|
64
|
+
get handoverState(): WorkHandover | null;
|
|
65
|
+
get primarySlotsRemaining(): number;
|
|
66
|
+
primarySlotState(requestId: string): 'reserved' | 'sent' | 'unknown' | 'accepted' | 'released' | undefined;
|
|
67
|
+
/** Runs and settles a consumed slot atomically within the dispatch-owned state transition. */
|
|
68
|
+
dispatchPrimarySlot(requestId: string, send: () => Promise<'sent' | 'unknown' | 'not_sent'> | 'sent' | 'unknown' | 'not_sent'): Promise<'sent' | 'unknown' | 'not_sent'>;
|
|
69
|
+
acceptPrimarySlot(requestId: string): void;
|
|
70
|
+
/** Raw callers cannot refund; use dispatchPrimarySlot for an authoritative not_sent result. */
|
|
71
|
+
releasePrimarySlot(rawRequestId: string): number;
|
|
72
|
+
switchPrimary(rawId: string): PrimaryEpoch;
|
|
73
|
+
consumePrimarySlot(rawRequestId: string): number;
|
|
74
|
+
failover(primaryId: string): {
|
|
75
|
+
readonly decisionId: string;
|
|
76
|
+
readonly primarySlotsRemaining: number;
|
|
77
|
+
readonly epoch: PrimaryEpoch;
|
|
78
|
+
};
|
|
79
|
+
acceptResponse(epoch: number, value: unknown): ResponseClassification;
|
|
80
|
+
classifyResponse(epoch: number, value: unknown): ResponseClassification;
|
|
81
|
+
/**
|
|
82
|
+
* Records accepted external work as a distinct handover event. Unlike acceptPrimarySlot,
|
|
83
|
+
* a new work-order ID is itself the accepted unit and charges one budget slot; when it
|
|
84
|
+
* matches an existing reservation, only reserved/sent/accepted states may transition here.
|
|
85
|
+
*/
|
|
86
|
+
acceptWorkOrder(workOrderId: string, state: {
|
|
87
|
+
readonly checkpoint: unknown;
|
|
88
|
+
readonly state: string;
|
|
89
|
+
}): WorkOrderState;
|
|
90
|
+
workOrder(workOrderId: string): WorkOrderState | undefined;
|
|
91
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { advisorId } from '../core/ids.js';
|
|
2
|
+
import { PrimaryRegistry } from './primary-registry.js';
|
|
3
|
+
/**
|
|
4
|
+
* In-memory primary budget and accepted-work state, scoped to this RoleEpoch instance and decision.
|
|
5
|
+
* A restart creates a fresh instance; this is not a persisted ledger and makes no restart-persistence claim.
|
|
6
|
+
* HandoverService.epoch and RoleEpoch.activeEpoch.epoch are separate counters and may diverge on failover.
|
|
7
|
+
* HandoverService owns the live authority fence.
|
|
8
|
+
*/
|
|
9
|
+
export class RoleEpoch {
|
|
10
|
+
epochHistory = [];
|
|
11
|
+
responseHistory = [];
|
|
12
|
+
eventHistory = [];
|
|
13
|
+
consumedRequests = new Set();
|
|
14
|
+
orders = new Map();
|
|
15
|
+
slotStates = new Map();
|
|
16
|
+
handedOver = null;
|
|
17
|
+
decision;
|
|
18
|
+
registry;
|
|
19
|
+
constructor(primaryId, options = {}) {
|
|
20
|
+
this.decision = options.decisionId ?? 'decision-unspecified';
|
|
21
|
+
this.registry = options.registry;
|
|
22
|
+
this.switchPrimary(primaryId);
|
|
23
|
+
}
|
|
24
|
+
get activeEpoch() { return this.epochHistory[this.epochHistory.length - 1]; }
|
|
25
|
+
get epochs() { return Object.freeze([...this.epochHistory]); }
|
|
26
|
+
get history() { return Object.freeze(this.responseHistory.map((entry) => Object.freeze({ ...entry, value: structuredClone(entry.value) }))); }
|
|
27
|
+
get events() { return Object.freeze([...this.eventHistory]); }
|
|
28
|
+
get handoverState() { return this.handedOver === null ? null : Object.freeze({ ...this.handedOver, checkpoint: structuredClone(this.handedOver.checkpoint) }); }
|
|
29
|
+
get primarySlotsRemaining() { return Math.max(0, 2 - this.consumedRequests.size); }
|
|
30
|
+
primarySlotState(requestId) { const state = this.slotStates.get(requestId); return state === 'sending' ? 'sent' : state; } // In-flight attempts are externally visible as sent and remain charged.
|
|
31
|
+
/** Runs and settles a consumed slot atomically within the dispatch-owned state transition. */
|
|
32
|
+
async dispatchPrimarySlot(requestId, send) {
|
|
33
|
+
if (typeof send !== 'function')
|
|
34
|
+
throw new TypeError('send operation required');
|
|
35
|
+
if (!this.consumedRequests.has(requestId))
|
|
36
|
+
throw new TypeError('unknown consumed primary slot');
|
|
37
|
+
const current = this.slotStates.get(requestId);
|
|
38
|
+
if (current !== 'reserved')
|
|
39
|
+
throw new Error(`primary slot in state ${current} cannot be dispatched`);
|
|
40
|
+
this.slotStates.set(requestId, 'sending');
|
|
41
|
+
let result;
|
|
42
|
+
try {
|
|
43
|
+
result = await send();
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
this.slotStates.set(requestId, 'unknown');
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
if (result === 'sent')
|
|
50
|
+
this.slotStates.set(requestId, 'sent');
|
|
51
|
+
else if (result === 'unknown')
|
|
52
|
+
this.slotStates.set(requestId, 'unknown');
|
|
53
|
+
else if (result === 'not_sent') {
|
|
54
|
+
this.consumedRequests.delete(requestId);
|
|
55
|
+
this.slotStates.set(requestId, 'released');
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
this.slotStates.set(requestId, 'unknown');
|
|
59
|
+
return 'unknown';
|
|
60
|
+
}
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
acceptPrimarySlot(requestId) {
|
|
64
|
+
const state = this.slotStates.get(requestId);
|
|
65
|
+
if (!this.consumedRequests.has(requestId) || (state !== 'sent' && state !== 'accepted'))
|
|
66
|
+
throw new Error(`primary slot in state ${state} cannot be accepted`);
|
|
67
|
+
this.slotStates.set(requestId, 'accepted');
|
|
68
|
+
}
|
|
69
|
+
/** Raw callers cannot refund; use dispatchPrimarySlot for an authoritative not_sent result. */
|
|
70
|
+
releasePrimarySlot(rawRequestId) {
|
|
71
|
+
if (typeof rawRequestId !== 'string' || !this.consumedRequests.has(rawRequestId))
|
|
72
|
+
throw new TypeError('unknown consumed primary request');
|
|
73
|
+
const state = this.slotStates.get(rawRequestId);
|
|
74
|
+
if (state !== 'reserved')
|
|
75
|
+
throw new Error(`primary slot in state ${state === 'sending' ? 'sent' : state} cannot be released`);
|
|
76
|
+
throw new Error('primary slot cannot be raw-released; settle through dispatch');
|
|
77
|
+
}
|
|
78
|
+
switchPrimary(rawId) {
|
|
79
|
+
const id = advisorId(rawId);
|
|
80
|
+
if (this.registry !== undefined && !this.registry.bindings.some((binding) => binding.advisorId === id))
|
|
81
|
+
throw new TypeError('primary must reference a registered advisor binding');
|
|
82
|
+
const previous = this.epochHistory[this.epochHistory.length - 1];
|
|
83
|
+
if (previous?.active)
|
|
84
|
+
this.epochHistory[this.epochHistory.length - 1] = Object.freeze({ ...previous, active: false });
|
|
85
|
+
const next = Object.freeze({ epoch: (previous?.epoch ?? 0) + 1, primaryId: id, active: true, changedAt: new Date().toISOString() });
|
|
86
|
+
this.epochHistory.push(next);
|
|
87
|
+
this.eventHistory.push(Object.freeze({ kind: 'role-switched', from: previous?.primaryId ?? null, to: id, epoch: next.epoch }));
|
|
88
|
+
const activeOrder = [...this.orders.values()].find((order) => order.state === 'running' || order.state === 'accepted');
|
|
89
|
+
if (activeOrder)
|
|
90
|
+
this.handedOver = Object.freeze({ ...activeOrder, checkpoint: structuredClone(activeOrder.checkpoint) });
|
|
91
|
+
return next;
|
|
92
|
+
}
|
|
93
|
+
consumePrimarySlot(rawRequestId) {
|
|
94
|
+
if (typeof rawRequestId !== 'string' || !/^[a-z][a-z0-9_-]{5,63}$/.test(rawRequestId))
|
|
95
|
+
throw new TypeError('valid primary request ID required');
|
|
96
|
+
if (this.consumedRequests.has(rawRequestId))
|
|
97
|
+
return 2 - this.consumedRequests.size;
|
|
98
|
+
if (this.consumedRequests.size >= 2)
|
|
99
|
+
throw new Error('primary slot budget exhausted');
|
|
100
|
+
this.consumedRequests.add(rawRequestId);
|
|
101
|
+
this.slotStates.set(rawRequestId, 'reserved');
|
|
102
|
+
return 2 - this.consumedRequests.size;
|
|
103
|
+
}
|
|
104
|
+
failover(primaryId) {
|
|
105
|
+
if (this.primarySlotsRemaining === 0)
|
|
106
|
+
throw new Error('primary slot budget exhausted');
|
|
107
|
+
const nextId = advisorId(primaryId);
|
|
108
|
+
if (this.registry !== undefined && !this.registry.bindings.some((binding) => binding.advisorId === nextId))
|
|
109
|
+
throw new TypeError('primary must reference a registered advisor binding');
|
|
110
|
+
const epoch = this.switchPrimary(nextId);
|
|
111
|
+
return Object.freeze({ decisionId: this.decision, primarySlotsRemaining: this.primarySlotsRemaining, epoch });
|
|
112
|
+
}
|
|
113
|
+
acceptResponse(epoch, value) {
|
|
114
|
+
if (!Number.isSafeInteger(epoch) || epoch < 1)
|
|
115
|
+
throw new TypeError('valid response epoch required');
|
|
116
|
+
const classification = this.activeEpoch.active && epoch === this.activeEpoch.epoch ? 'current' : 'stale';
|
|
117
|
+
const snapshot = structuredClone(value);
|
|
118
|
+
this.responseHistory.push(Object.freeze({ epoch, value: snapshot, classification }));
|
|
119
|
+
this.eventHistory.push(Object.freeze({ kind: 'response-recorded', epoch, classification }));
|
|
120
|
+
return Object.freeze({ classification, historyRecorded: true, dispatched: false, ...(classification === 'current' ? { value: structuredClone(snapshot) } : {}) });
|
|
121
|
+
}
|
|
122
|
+
classifyResponse(epoch, value) { return this.acceptResponse(epoch, value); }
|
|
123
|
+
/**
|
|
124
|
+
* Records accepted external work as a distinct handover event. Unlike acceptPrimarySlot,
|
|
125
|
+
* a new work-order ID is itself the accepted unit and charges one budget slot; when it
|
|
126
|
+
* matches an existing reservation, only reserved/sent/accepted states may transition here.
|
|
127
|
+
*/
|
|
128
|
+
acceptWorkOrder(workOrderId, state) {
|
|
129
|
+
if (typeof workOrderId !== 'string' || !/^[a-z][a-z0-9_-]{5,63}$/.test(workOrderId) || !state || typeof state.state !== 'string' || !state.state.trim())
|
|
130
|
+
throw new TypeError('valid accepted work order state required');
|
|
131
|
+
if (this.orders.has(workOrderId))
|
|
132
|
+
throw new TypeError('accepted work order is immutable and unique');
|
|
133
|
+
if ([...this.orders.values()].some((order) => order.state === 'running' || order.state === 'accepted'))
|
|
134
|
+
throw new Error('an accepted work order is already active');
|
|
135
|
+
const reserved = this.consumedRequests.has(workOrderId);
|
|
136
|
+
const priorState = this.slotStates.get(workOrderId);
|
|
137
|
+
if (reserved && priorState !== 'reserved' && priorState !== 'sent' && priorState !== 'accepted')
|
|
138
|
+
throw new Error(`primary slot in state ${priorState} cannot accept work`);
|
|
139
|
+
if (!reserved && this.consumedRequests.size >= 2)
|
|
140
|
+
throw new Error('primary slot budget exhausted');
|
|
141
|
+
if (!reserved)
|
|
142
|
+
this.consumedRequests.add(workOrderId);
|
|
143
|
+
const order = Object.freeze({ workOrderId, checkpoint: structuredClone(state.checkpoint), state: state.state, dispatchCount: 1 });
|
|
144
|
+
this.orders.set(workOrderId, order);
|
|
145
|
+
this.slotStates.set(workOrderId, 'accepted');
|
|
146
|
+
this.eventHistory.push(Object.freeze({ kind: 'work-order-accepted', workOrderId }));
|
|
147
|
+
return order;
|
|
148
|
+
}
|
|
149
|
+
workOrder(workOrderId) {
|
|
150
|
+
const order = this.orders.get(workOrderId);
|
|
151
|
+
return order === undefined ? undefined : Object.freeze({ ...order, checkpoint: structuredClone(order.checkpoint) });
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
//# sourceMappingURL=role-epoch.js.map
|