@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,167 @@
|
|
|
1
|
+
import { PrimaryRegistry } from './primary-registry.js';
|
|
2
|
+
import { RoleEpoch } from './role-epoch.js';
|
|
3
|
+
const copyRoleOptions = (decisionId, registry) => registry === undefined ? { decisionId } : { decisionId, registry };
|
|
4
|
+
const copyEngineOptions = (decisionId, primaryId, loopLimit, registry) => registry === undefined ? { decisionId, primaryId, loopLimit } : { decisionId, primaryId, loopLimit, registry };
|
|
5
|
+
/** In-memory decision journal. Exported snapshots are detached, immutable restart records. */
|
|
6
|
+
export class DecisionEngine {
|
|
7
|
+
state;
|
|
8
|
+
roles;
|
|
9
|
+
constructor(options) {
|
|
10
|
+
if (!options || typeof options.decisionId !== 'string' || !options.decisionId.trim() || typeof options.primaryId !== 'string' || !options.primaryId.trim())
|
|
11
|
+
throw new TypeError('decisionId and primaryId required');
|
|
12
|
+
const loopLimit = options.loopLimit ?? 2;
|
|
13
|
+
if (!Number.isSafeInteger(loopLimit) || loopLimit < 1)
|
|
14
|
+
throw new TypeError('loopLimit must be positive');
|
|
15
|
+
this.roles = new RoleEpoch(options.primaryId, copyRoleOptions(options.decisionId, options.registry));
|
|
16
|
+
this.state = { decisionId: options.decisionId, primaryId: options.primaryId, primary: [], reviewers: [], audit: [], outcome: 'open', fingerprints: [], fingerprintCounts: {}, loopLimit, snapshotRevision: 0, synthesis: null, orders: [] };
|
|
17
|
+
}
|
|
18
|
+
static restore(snapshot, registry) {
|
|
19
|
+
validateSnapshot(snapshot);
|
|
20
|
+
const engine = new DecisionEngine(copyEngineOptions(snapshot.decisionId, snapshot.primaryId, snapshot.loopLimit, registry));
|
|
21
|
+
engine.state = cloneSnapshot(snapshot);
|
|
22
|
+
return engine;
|
|
23
|
+
}
|
|
24
|
+
snapshot() { return freezeSnapshot(this.state); }
|
|
25
|
+
reservePrimary(requestId, purpose) {
|
|
26
|
+
validateId(requestId);
|
|
27
|
+
if (!['bootstrap', 'repair', 'continue'].includes(purpose))
|
|
28
|
+
throw new TypeError('invalid primary purpose');
|
|
29
|
+
const existing = this.state.primary.find((slot) => slot.requestId === requestId);
|
|
30
|
+
if (existing)
|
|
31
|
+
return cloneValue(existing);
|
|
32
|
+
if (this.state.outcome !== 'open')
|
|
33
|
+
throw new Error('decision is terminal');
|
|
34
|
+
if (this.state.primary.filter((slot) => slot.status !== 'released').length >= 2) {
|
|
35
|
+
this.state.outcome = 'needs_owner';
|
|
36
|
+
this.log({ kind: 'needs-owner', reason: 'primary budget exhausted' });
|
|
37
|
+
this.touch();
|
|
38
|
+
throw new Error('primary slot budget exhausted; needs-owner is terminal');
|
|
39
|
+
}
|
|
40
|
+
const call = Object.freeze({ requestId, advisorId: this.roles.activeEpoch.primaryId, purpose, status: 'prepared' });
|
|
41
|
+
this.roles.consumePrimarySlot(requestId); // T07-01 enforces the shared two-slot invariant.
|
|
42
|
+
this.state.primary.push(call);
|
|
43
|
+
this.log({ kind: 'primary-reserved', requestId, purpose });
|
|
44
|
+
this.touch();
|
|
45
|
+
return cloneValue(call);
|
|
46
|
+
}
|
|
47
|
+
settlePrimary(requestId, result) {
|
|
48
|
+
const index = this.primaryIndex(requestId), slot = this.state.primary[index];
|
|
49
|
+
if (slot.status !== 'prepared' && slot.status !== 'unknown')
|
|
50
|
+
throw new TypeError('primary request is not prepared or reconcilable');
|
|
51
|
+
const status = result === 'sent' ? 'sent' : result === 'unknown' ? 'unknown' : 'released';
|
|
52
|
+
this.state.primary[index] = Object.freeze({ ...slot, status });
|
|
53
|
+
this.log({ kind: 'primary-settled', requestId, reason: status });
|
|
54
|
+
this.touch();
|
|
55
|
+
return status;
|
|
56
|
+
}
|
|
57
|
+
reconcilePrimary(requestId, result) {
|
|
58
|
+
const status = this.settlePrimary(requestId, result);
|
|
59
|
+
return status === 'sent' ? 'consumed' : status === 'unknown' ? 'needs_reconciliation' : 'released';
|
|
60
|
+
}
|
|
61
|
+
finishPrimary(requestId, reply) {
|
|
62
|
+
const index = this.primaryIndex(requestId), slot = this.state.primary[index];
|
|
63
|
+
if (slot.status !== 'sent')
|
|
64
|
+
throw new TypeError('primary response requires a sent request');
|
|
65
|
+
if (!reply || typeof reply !== 'object')
|
|
66
|
+
throw new TypeError('structured primary reply required');
|
|
67
|
+
if (reply.kind === 'review-request') {
|
|
68
|
+
if (typeof reply.reason !== 'string' || !reply.reason.trim() || !Array.isArray(reply.reviewers) || !reply.reviewers.length || reply.reviewers.some((id) => typeof id !== 'string' || !id.trim()))
|
|
69
|
+
throw new TypeError('invalid reviewer request');
|
|
70
|
+
this.log({ kind: 'review-requested', requestId, reason: reply.reason });
|
|
71
|
+
this.touch();
|
|
72
|
+
if (this.state.primary.filter((call) => call.status !== 'released').length >= 2) {
|
|
73
|
+
this.state.outcome = 'needs_owner';
|
|
74
|
+
this.log({ kind: 'needs-owner', reason: 'primary exhausted while requesting more review' });
|
|
75
|
+
this.touch();
|
|
76
|
+
return Object.freeze({ outcome: 'needs_owner' });
|
|
77
|
+
}
|
|
78
|
+
return Object.freeze({ outcome: 'review_requested' }); // one bounded reviewer request.
|
|
79
|
+
}
|
|
80
|
+
if (reply.kind !== 'final' || !['execute', 'investigate', 'needs_owner', 'done', 'reject'].includes(reply.outcome) || typeof reply.rationale !== 'string' || !reply.rationale.trim())
|
|
81
|
+
throw new TypeError('invalid final decision');
|
|
82
|
+
this.state.outcome = reply.outcome === 'needs_owner' ? 'needs_owner' : 'final';
|
|
83
|
+
this.log({ kind: 'decision-final', requestId, reason: reply.rationale });
|
|
84
|
+
this.touch();
|
|
85
|
+
return Object.freeze({ outcome: this.state.outcome });
|
|
86
|
+
}
|
|
87
|
+
reserveReviewers(reviewerIds, evidenceRevision) {
|
|
88
|
+
this.assertOpen();
|
|
89
|
+
if (!Array.isArray(reviewerIds) || !reviewerIds.length || !Number.isSafeInteger(evidenceRevision) || evidenceRevision < 1)
|
|
90
|
+
throw new TypeError('reviewers and positive evidence revision required');
|
|
91
|
+
if (new Set(reviewerIds).size !== reviewerIds.length || reviewerIds.some((id) => typeof id !== 'string' || !id.trim()))
|
|
92
|
+
throw new TypeError('unique reviewer IDs required');
|
|
93
|
+
const calls = reviewerIds.map((reviewerId, index) => Object.freeze({ requestId: `review-${this.state.decisionId}-${this.state.reviewers.length + index + 1}`, reviewerId, evidenceRevision, status: 'pending' }));
|
|
94
|
+
this.state.reviewers.push(...calls);
|
|
95
|
+
for (const call of calls)
|
|
96
|
+
this.log({ kind: 'reviewer-dispatched', requestId: call.requestId });
|
|
97
|
+
this.touch();
|
|
98
|
+
return Object.freeze(calls.map((call) => cloneValue(call)));
|
|
99
|
+
}
|
|
100
|
+
submitReviewerOpinion(requestId, opinion) {
|
|
101
|
+
const index = this.state.reviewers.findIndex((call) => call.requestId === requestId);
|
|
102
|
+
if (index < 0)
|
|
103
|
+
throw new TypeError('unknown reviewer request');
|
|
104
|
+
const call = this.state.reviewers[index];
|
|
105
|
+
if (call.status === 'timed_out' || this.state.synthesis !== null) {
|
|
106
|
+
this.log({ kind: 'late-review-ignored', requestId });
|
|
107
|
+
this.touch();
|
|
108
|
+
return 'late_ignored';
|
|
109
|
+
}
|
|
110
|
+
this.state.reviewers[index] = Object.freeze({ ...call, status: 'submitted', opinion: cloneValue(opinion) });
|
|
111
|
+
this.touch();
|
|
112
|
+
return 'accepted';
|
|
113
|
+
}
|
|
114
|
+
timeoutReviewer(requestId) { const i = this.state.reviewers.findIndex((x) => x.requestId === requestId); if (i < 0 || this.state.reviewers[i].status !== 'pending')
|
|
115
|
+
throw new TypeError('reviewer is not pending'); this.state.reviewers[i] = Object.freeze({ ...this.state.reviewers[i], status: 'timed_out' }); this.log({ kind: 'reviewer-timeout', requestId }); this.touch(); }
|
|
116
|
+
synthesizeReviewers() { if (this.state.reviewers.some((x) => x.status === 'pending'))
|
|
117
|
+
throw new Error('all reviewer calls must settle before synthesis'); const opinions = this.state.reviewers.filter((x) => x.status === 'submitted').map((x) => cloneValue(x.opinion && typeof x.opinion === 'object' && 'opinion' in x.opinion ? x.opinion.opinion : x.opinion)); this.state.synthesis = opinions; this.touch(); return Object.freeze(opinions); }
|
|
118
|
+
settleUnavailableFallback() { if (this.state.outcome !== 'open')
|
|
119
|
+
return; this.state.outcome = this.state.reviewers.some((x) => x.status === 'pending') ? 'needs_owner' : 'final'; this.log({ kind: this.state.outcome === 'final' ? 'final-with-coverage' : 'needs-owner', reason: 'fallback unavailable' }); this.touch(); }
|
|
120
|
+
recordProblem(raw) { if (typeof raw !== 'string' || !raw.trim())
|
|
121
|
+
throw new TypeError('problem description required'); const fp = normalizeProblemFingerprint(raw); const count = (this.state.fingerprintCounts[fp] ?? 0) + 1; this.state.fingerprintCounts[fp] = count; if (!this.state.fingerprints.includes(fp))
|
|
122
|
+
this.state.fingerprints.push(fp); this.log({ kind: 'problem-observed', reason: fp }); if (count >= this.state.loopLimit) {
|
|
123
|
+
this.state.outcome = 'needs_owner';
|
|
124
|
+
this.log({ kind: 'needs-owner', reason: 'same problem reached loop ceiling' });
|
|
125
|
+
this.touch();
|
|
126
|
+
return 'needs_owner';
|
|
127
|
+
} this.touch(); return 'continue'; }
|
|
128
|
+
recordAcceptedOrder(workOrderId, payload) { validateId(workOrderId); if (this.state.orders.some((x) => x.workOrderId === workOrderId))
|
|
129
|
+
throw new TypeError('accepted order is immutable and unique'); this.state.orders.push(Object.freeze({ workOrderId, payload: cloneValue(payload), dispatchCount: 1, state: 'accepted' })); this.log({ kind: 'order-accepted', requestId: workOrderId }); this.touch(); }
|
|
130
|
+
reconcileAcceptedOrder(workOrderId, result) { const i = this.state.orders.findIndex((x) => x.workOrderId === workOrderId); if (i < 0)
|
|
131
|
+
throw new TypeError('unknown accepted order'); if (result === 'accepted')
|
|
132
|
+
return 'accepted'; if (result === 'unknown') {
|
|
133
|
+
this.state.orders[i] = Object.freeze({ ...this.state.orders[i], state: 'unknown' });
|
|
134
|
+
this.state.outcome = 'needs_owner';
|
|
135
|
+
this.log({ kind: 'order-reconciliation-unknown', requestId: workOrderId });
|
|
136
|
+
this.touch();
|
|
137
|
+
return 'needs_owner';
|
|
138
|
+
} this.state.orders[i] = Object.freeze({ ...this.state.orders[i], state: 'reconciled' }); this.touch(); return 'not_received'; }
|
|
139
|
+
replayOrder(workOrderId) { if (this.state.orders.some((x) => x.workOrderId === workOrderId))
|
|
140
|
+
throw new Error('accepted order mutation cannot be replayed'); throw new TypeError('unknown order'); }
|
|
141
|
+
primaryIndex(id) { const i = this.state.primary.findIndex((x) => x.requestId === id); if (i < 0)
|
|
142
|
+
throw new TypeError('unknown primary request'); return i; }
|
|
143
|
+
assertOpen() { if (this.state.outcome !== 'open')
|
|
144
|
+
throw new Error('decision is terminal'); }
|
|
145
|
+
log(entry) { this.state.audit.push(Object.freeze(entry)); }
|
|
146
|
+
touch() { this.state.snapshotRevision++; }
|
|
147
|
+
}
|
|
148
|
+
function validateId(id) { if (typeof id !== 'string' || !/^[a-z][a-z0-9_-]{5,63}$/.test(id))
|
|
149
|
+
throw new TypeError('valid request/order ID required'); }
|
|
150
|
+
export function normalizeProblemFingerprint(raw) { if (typeof raw !== 'string' || !raw.trim())
|
|
151
|
+
throw new TypeError('problem description required'); const normalized = raw.toLowerCase().replace(/\b\d{4}-\d\d-\d\d(?:t\d\d:\d\d(?::\d\d(?:\.\d+)?)?z)?\b/gi, ' ').replace(/\b\d{1,2}:\d{2}(?::\d{2})?\b/g, ' ').replace(/\b(at|on|the|a|an|while|when|occurred|happened|response|reading|read|got|was|is|during)\b/g, ' ').replace(/\b(time\s*out|timed\s*out|timeout)\b/g, ' timeout ').replace(/[^a-z0-9]+/g, ' ').trim().split(/\s+/).filter(Boolean).sort(); return normalized.join(' '); }
|
|
152
|
+
function cloneValue(value) { return structuredClone(value); }
|
|
153
|
+
function cloneSnapshot(s) { return structuredClone(s); }
|
|
154
|
+
function freezeSnapshot(s) { return deepFreeze(cloneSnapshot(s)); }
|
|
155
|
+
function deepFreeze(value) { if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
156
|
+
Object.values(value).forEach((v) => deepFreeze(v));
|
|
157
|
+
Object.freeze(value);
|
|
158
|
+
} return value; }
|
|
159
|
+
function validateSnapshot(s) { if (!s || typeof s !== 'object' || typeof s.decisionId !== 'string' || typeof s.primaryId !== 'string' || !Array.isArray(s.primary) || !Array.isArray(s.reviewers) || !Array.isArray(s.audit) || s.primary.length > 2 || !Number.isSafeInteger(s.snapshotRevision) || s.snapshotRevision < 0)
|
|
160
|
+
throw new TypeError('invalid decision snapshot'); const ids = new Set(); for (const slot of s.primary) {
|
|
161
|
+
validateId(slot.requestId);
|
|
162
|
+
if (ids.has(slot.requestId) || !['prepared', 'sent', 'unknown', 'released'].includes(slot.status))
|
|
163
|
+
throw new TypeError('invalid or duplicate primary slot');
|
|
164
|
+
ids.add(slot.requestId);
|
|
165
|
+
} if (s.outcome !== 'open' && s.outcome !== 'final' && s.outcome !== 'needs_owner')
|
|
166
|
+
throw new TypeError('invalid outcome'); }
|
|
167
|
+
//# sourceMappingURL=decision.js.map
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
type FailureKind = 'quota' | 'login' | 'network' | 'unknown';
|
|
2
|
+
export interface ProviderFailure {
|
|
3
|
+
readonly kind: FailureKind;
|
|
4
|
+
readonly message?: string;
|
|
5
|
+
}
|
|
6
|
+
export interface FailurePolicy {
|
|
7
|
+
readonly kind: FailureKind;
|
|
8
|
+
readonly automaticFailover: boolean;
|
|
9
|
+
readonly retryLimit: number;
|
|
10
|
+
readonly cooldown: boolean;
|
|
11
|
+
readonly requiresOwner: boolean;
|
|
12
|
+
}
|
|
13
|
+
export interface HandoverOptions {
|
|
14
|
+
readonly decisionId: string;
|
|
15
|
+
readonly primaryId: string;
|
|
16
|
+
readonly cooldownMs?: number;
|
|
17
|
+
readonly now?: () => number;
|
|
18
|
+
readonly instanceId?: string;
|
|
19
|
+
readonly networkRetryLimit?: number;
|
|
20
|
+
}
|
|
21
|
+
export interface HandoverContext {
|
|
22
|
+
readonly decision: unknown;
|
|
23
|
+
readonly consumedSlots: readonly string[];
|
|
24
|
+
readonly currentWork: Readonly<{
|
|
25
|
+
id: string;
|
|
26
|
+
state: string;
|
|
27
|
+
checkpoint: unknown;
|
|
28
|
+
dispatchCount: number;
|
|
29
|
+
}> | null;
|
|
30
|
+
}
|
|
31
|
+
export interface HandoverFence {
|
|
32
|
+
readonly epoch: number;
|
|
33
|
+
readonly primaryId: string;
|
|
34
|
+
readonly instanceId: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* `not_sent` is a contract that no external side effect occurred. A thrown exception or
|
|
38
|
+
* ambiguous outcome is treated as unknown and remains charged; return `not_sent` only
|
|
39
|
+
* when the callback can guarantee the operation was not externally applied.
|
|
40
|
+
*/
|
|
41
|
+
export type PrimarySlotSend = () => Promise<'sent' | 'unknown' | 'not_sent'> | 'sent' | 'unknown' | 'not_sent';
|
|
42
|
+
/** SIMULATED provider-state seam: in-memory policies/fencing only; live provider observation is not performed here. */
|
|
43
|
+
export declare class HandoverService {
|
|
44
|
+
private primary;
|
|
45
|
+
private epoch;
|
|
46
|
+
private readonly roles;
|
|
47
|
+
private readonly instanceId;
|
|
48
|
+
private readonly networkRetryLimit;
|
|
49
|
+
private readonly networkRetries;
|
|
50
|
+
private cooldowns;
|
|
51
|
+
private readonly events;
|
|
52
|
+
private history;
|
|
53
|
+
private transferred;
|
|
54
|
+
private dispatched;
|
|
55
|
+
private terminal;
|
|
56
|
+
private exhaustedResult;
|
|
57
|
+
private readonly clock;
|
|
58
|
+
private readonly cooldownMs;
|
|
59
|
+
readonly decisionId: string;
|
|
60
|
+
readonly persistence: 'in-memory';
|
|
61
|
+
constructor(options: HandoverOptions);
|
|
62
|
+
get currentPrimary(): string;
|
|
63
|
+
get currentFence(): HandoverFence;
|
|
64
|
+
get primarySlotsRemaining(): number;
|
|
65
|
+
get responseHistory(): readonly {
|
|
66
|
+
readonly fence: HandoverFence;
|
|
67
|
+
readonly value: any;
|
|
68
|
+
}[];
|
|
69
|
+
get audit(): readonly {
|
|
70
|
+
readonly kind: string;
|
|
71
|
+
readonly reason: string;
|
|
72
|
+
readonly provider?: string;
|
|
73
|
+
}[];
|
|
74
|
+
classifyFailure(failure: ProviderFailure): ProviderFailure;
|
|
75
|
+
failurePolicy(kind: FailureKind): FailurePolicy;
|
|
76
|
+
recordFailure(failure: ProviderFailure): FailurePolicy;
|
|
77
|
+
recordNetworkRetry(requestId: string): boolean;
|
|
78
|
+
consumePrimarySlot(requestId: string): number;
|
|
79
|
+
primarySlotState(requestId: string): 'reserved' | 'sent' | 'unknown' | 'accepted' | 'released' | undefined;
|
|
80
|
+
acceptPrimarySlot(requestId: string): void;
|
|
81
|
+
releasePrimarySlot(requestId: string): number;
|
|
82
|
+
/**
|
|
83
|
+
* Runs the only valid settlement path for a consumed primary slot. The callback's `not_sent`
|
|
84
|
+
* return is a guarantee that no external side effect occurred; exceptions/ambiguous values
|
|
85
|
+
* are charged as unknown.
|
|
86
|
+
*/
|
|
87
|
+
dispatchPrimarySlot(requestId: string, send: PrimarySlotSend): Promise<'sent' | 'unknown' | 'not_sent'>;
|
|
88
|
+
failover(input: {
|
|
89
|
+
readonly failure: ProviderFailure;
|
|
90
|
+
readonly candidates: readonly string[];
|
|
91
|
+
readonly now?: number;
|
|
92
|
+
}): {
|
|
93
|
+
readonly decisionId: string;
|
|
94
|
+
readonly primaryId: string;
|
|
95
|
+
readonly primarySlotsRemaining: number;
|
|
96
|
+
readonly reason: string;
|
|
97
|
+
};
|
|
98
|
+
manualSwitch(primaryId: string, reason?: string): HandoverFence;
|
|
99
|
+
availableProviders(providers: readonly string[], now?: number): readonly string[];
|
|
100
|
+
transfer(context: HandoverContext): HandoverContext;
|
|
101
|
+
dispatchWorkOrder(workOrderId: string): boolean;
|
|
102
|
+
dispatchCount(workOrderId: string): number;
|
|
103
|
+
recordPrimaryResponse(fence: HandoverFence, value: unknown): 'current' | 'stale';
|
|
104
|
+
authorizeSideEffect(fence: HandoverFence): boolean;
|
|
105
|
+
exhaustFallbacks(input: {
|
|
106
|
+
readonly reviewerTimedOut: boolean;
|
|
107
|
+
readonly unavailable: readonly string[];
|
|
108
|
+
readonly coverage: readonly string[];
|
|
109
|
+
}): {
|
|
110
|
+
readonly terminal: true;
|
|
111
|
+
readonly outcome: 'final' | 'needs-owner';
|
|
112
|
+
readonly coverage: readonly string[];
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export {};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { advisorId } from '../core/ids.js';
|
|
2
|
+
import { RoleEpoch } from './role-epoch.js';
|
|
3
|
+
/** SIMULATED provider-state seam: in-memory policies/fencing only; live provider observation is not performed here. */
|
|
4
|
+
export class HandoverService {
|
|
5
|
+
primary;
|
|
6
|
+
epoch = 1;
|
|
7
|
+
roles;
|
|
8
|
+
instanceId;
|
|
9
|
+
networkRetryLimit;
|
|
10
|
+
networkRetries = new Map();
|
|
11
|
+
cooldowns = new Map();
|
|
12
|
+
events = [];
|
|
13
|
+
history = [];
|
|
14
|
+
transferred = null;
|
|
15
|
+
dispatched = new Set();
|
|
16
|
+
terminal = false;
|
|
17
|
+
exhaustedResult = null;
|
|
18
|
+
clock;
|
|
19
|
+
cooldownMs;
|
|
20
|
+
decisionId;
|
|
21
|
+
persistence = 'in-memory';
|
|
22
|
+
constructor(options) {
|
|
23
|
+
if (!options || typeof options.decisionId !== 'string' || !options.decisionId.trim())
|
|
24
|
+
throw new TypeError('decision ID required');
|
|
25
|
+
this.decisionId = options.decisionId;
|
|
26
|
+
this.primary = advisorId(options.primaryId);
|
|
27
|
+
this.roles = new RoleEpoch(this.primary, { decisionId: this.decisionId });
|
|
28
|
+
this.clock = options.now ?? Date.now;
|
|
29
|
+
this.cooldownMs = options.cooldownMs ?? 60_000;
|
|
30
|
+
this.instanceId = options.instanceId ?? `handover-${Math.random().toString(36).slice(2)}`;
|
|
31
|
+
this.networkRetryLimit = options.networkRetryLimit ?? 2;
|
|
32
|
+
if (!Number.isSafeInteger(this.cooldownMs) || this.cooldownMs < 0)
|
|
33
|
+
throw new TypeError('non-negative cooldown required');
|
|
34
|
+
if (!Number.isSafeInteger(this.networkRetryLimit) || this.networkRetryLimit < 0)
|
|
35
|
+
throw new TypeError('non-negative network retry limit required');
|
|
36
|
+
if (typeof this.instanceId !== 'string' || !this.instanceId.trim())
|
|
37
|
+
throw new TypeError('instance ID required');
|
|
38
|
+
}
|
|
39
|
+
get currentPrimary() { return this.primary; }
|
|
40
|
+
get currentFence() { return Object.freeze({ epoch: this.epoch, primaryId: this.primary, instanceId: this.instanceId }); }
|
|
41
|
+
get primarySlotsRemaining() { return this.roles.primarySlotsRemaining; }
|
|
42
|
+
get responseHistory() { return Object.freeze(this.history.map((entry) => Object.freeze({ fence: entry.fence, value: structuredClone(entry.value) }))); }
|
|
43
|
+
get audit() { return Object.freeze(this.events.map((event) => Object.freeze({ ...event }))); }
|
|
44
|
+
classifyFailure(failure) {
|
|
45
|
+
if (!failure || !['quota', 'login', 'network', 'unknown'].includes(failure.kind))
|
|
46
|
+
throw new TypeError('provider failure kind required');
|
|
47
|
+
return Object.freeze({ ...failure });
|
|
48
|
+
}
|
|
49
|
+
failurePolicy(kind) {
|
|
50
|
+
if (!['quota', 'login', 'network', 'unknown'].includes(kind))
|
|
51
|
+
throw new TypeError('provider failure kind required');
|
|
52
|
+
if (kind === 'quota')
|
|
53
|
+
return Object.freeze({ kind, automaticFailover: true, retryLimit: 0, cooldown: true, requiresOwner: false });
|
|
54
|
+
if (kind === 'login')
|
|
55
|
+
return Object.freeze({ kind, automaticFailover: false, retryLimit: 0, cooldown: false, requiresOwner: true });
|
|
56
|
+
if (kind === 'network')
|
|
57
|
+
return Object.freeze({ kind, automaticFailover: false, retryLimit: this.networkRetryLimit, cooldown: false, requiresOwner: false });
|
|
58
|
+
return Object.freeze({ kind, automaticFailover: false, retryLimit: 0, cooldown: false, requiresOwner: true });
|
|
59
|
+
}
|
|
60
|
+
recordFailure(failure) {
|
|
61
|
+
const classified = this.classifyFailure(failure), policy = this.failurePolicy(classified.kind);
|
|
62
|
+
if (classified.kind === 'quota')
|
|
63
|
+
this.cooldowns.set(this.primary, this.clock() + this.cooldownMs);
|
|
64
|
+
if (classified.kind === 'login')
|
|
65
|
+
this.events.push(Object.freeze({ kind: 'login-owner-required', reason: 'login failure requires owner re-authentication; not counted as quota', provider: this.primary }));
|
|
66
|
+
else if (classified.kind === 'network')
|
|
67
|
+
this.events.push(Object.freeze({ kind: 'network-retry-bounded', reason: `network retry limit ${policy.retryLimit}`, provider: this.primary }));
|
|
68
|
+
else if (classified.kind === 'quota')
|
|
69
|
+
this.events.push(Object.freeze({ kind: 'quota-cooldown', reason: 'quota failure recorded; cooldown before failover', provider: this.primary }));
|
|
70
|
+
else
|
|
71
|
+
this.events.push(Object.freeze({ kind: 'unknown-owner-required', reason: 'unknown failure requires owner review', provider: this.primary }));
|
|
72
|
+
return policy;
|
|
73
|
+
}
|
|
74
|
+
recordNetworkRetry(requestId) {
|
|
75
|
+
if (typeof requestId !== 'string' || !requestId.trim())
|
|
76
|
+
throw new TypeError('request ID required');
|
|
77
|
+
const attempts = this.networkRetries.get(requestId) ?? 0;
|
|
78
|
+
if (attempts >= this.networkRetryLimit)
|
|
79
|
+
return false;
|
|
80
|
+
this.networkRetries.set(requestId, attempts + 1);
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
consumePrimarySlot(requestId) { return this.roles.consumePrimarySlot(requestId); }
|
|
84
|
+
primarySlotState(requestId) { return this.roles.primarySlotState(requestId); }
|
|
85
|
+
acceptPrimarySlot(requestId) { this.roles.acceptPrimarySlot(requestId); }
|
|
86
|
+
releasePrimarySlot(requestId) { return this.roles.releasePrimarySlot(requestId); }
|
|
87
|
+
/**
|
|
88
|
+
* Runs the only valid settlement path for a consumed primary slot. The callback's `not_sent`
|
|
89
|
+
* return is a guarantee that no external side effect occurred; exceptions/ambiguous values
|
|
90
|
+
* are charged as unknown.
|
|
91
|
+
*/
|
|
92
|
+
async dispatchPrimarySlot(requestId, send) {
|
|
93
|
+
if (typeof send !== 'function')
|
|
94
|
+
throw new TypeError('send operation required');
|
|
95
|
+
return this.roles.dispatchPrimarySlot(requestId, send);
|
|
96
|
+
}
|
|
97
|
+
failover(input) {
|
|
98
|
+
if (this.terminal)
|
|
99
|
+
throw new Error('decision is terminal');
|
|
100
|
+
const failure = this.classifyFailure(input?.failure);
|
|
101
|
+
if (failure.kind !== 'quota')
|
|
102
|
+
throw new Error('quota failure required for automatic failover');
|
|
103
|
+
if (this.primarySlotsRemaining === 0)
|
|
104
|
+
throw new Error('primary slot budget exhausted');
|
|
105
|
+
const now = input.now ?? this.clock();
|
|
106
|
+
if (!Number.isFinite(now))
|
|
107
|
+
throw new TypeError('valid failover timestamp required');
|
|
108
|
+
const candidates = (input.candidates ?? []).map((id) => advisorId(id));
|
|
109
|
+
// The exhausted primary cooldown is intentionally recorded before checking terminal fallback availability.
|
|
110
|
+
this.cooldowns.set(this.primary, now + this.cooldownMs);
|
|
111
|
+
const next = candidates.find((id) => id !== this.primary && (this.cooldowns.get(id) ?? -Infinity) <= now);
|
|
112
|
+
if (!next) {
|
|
113
|
+
this.terminal = true;
|
|
114
|
+
throw new Error('no available fallback; decision is terminal');
|
|
115
|
+
}
|
|
116
|
+
const prior = this.primary;
|
|
117
|
+
this.primary = next;
|
|
118
|
+
this.epoch++;
|
|
119
|
+
const reason = `quota failure on ${prior}; selected fallback ${next}`;
|
|
120
|
+
this.events.push(Object.freeze({ kind: 'failover', reason, provider: next }));
|
|
121
|
+
return Object.freeze({ decisionId: this.decisionId, primaryId: next, primarySlotsRemaining: this.primarySlotsRemaining, reason });
|
|
122
|
+
}
|
|
123
|
+
manualSwitch(primaryId, reason = 'manual owner switch') {
|
|
124
|
+
if (this.terminal)
|
|
125
|
+
throw new Error('decision is terminal');
|
|
126
|
+
if (typeof reason !== 'string' || !reason.trim())
|
|
127
|
+
throw new TypeError('switch reason required');
|
|
128
|
+
const next = advisorId(primaryId);
|
|
129
|
+
this.primary = next;
|
|
130
|
+
this.epoch++;
|
|
131
|
+
this.events.push(Object.freeze({ kind: 'manual-switch', reason, provider: next }));
|
|
132
|
+
return this.currentFence;
|
|
133
|
+
}
|
|
134
|
+
availableProviders(providers, now = this.clock()) {
|
|
135
|
+
if (!Number.isFinite(now))
|
|
136
|
+
throw new TypeError('valid provider observation timestamp required');
|
|
137
|
+
return Object.freeze(providers.map((id) => advisorId(id)).filter((id) => (this.cooldowns.get(id) ?? -Infinity) <= now));
|
|
138
|
+
}
|
|
139
|
+
transfer(context) {
|
|
140
|
+
if (!context || !Array.isArray(context.consumedSlots) || !(context.currentWork === null || context.currentWork && typeof context.currentWork.id === 'string'))
|
|
141
|
+
throw new TypeError('decision, slots and current work state required');
|
|
142
|
+
if (context.currentWork && (!Number.isSafeInteger(context.currentWork.dispatchCount) || context.currentWork.dispatchCount !== 1))
|
|
143
|
+
throw new TypeError('accepted work must retain exactly one dispatch');
|
|
144
|
+
const cloned = structuredClone(context);
|
|
145
|
+
if (this.transferred === null)
|
|
146
|
+
this.transferred = deepFreeze(cloned);
|
|
147
|
+
else if (JSON.stringify(this.transferred) !== JSON.stringify(cloned))
|
|
148
|
+
throw new Error('handover context is immutable once transferred');
|
|
149
|
+
if (cloned.currentWork)
|
|
150
|
+
this.dispatched.add(cloned.currentWork.id);
|
|
151
|
+
return deepFreeze(structuredClone(this.transferred));
|
|
152
|
+
}
|
|
153
|
+
dispatchWorkOrder(workOrderId) {
|
|
154
|
+
if (typeof workOrderId !== 'string' || !workOrderId.trim())
|
|
155
|
+
throw new TypeError('work order ID required');
|
|
156
|
+
if (this.dispatched.has(workOrderId))
|
|
157
|
+
throw new Error('work order already received; redispatch refused');
|
|
158
|
+
this.dispatched.add(workOrderId);
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
dispatchCount(workOrderId) { return this.dispatched.has(workOrderId) ? 1 : 0; }
|
|
162
|
+
recordPrimaryResponse(fence, value) {
|
|
163
|
+
if (!fence || !Number.isSafeInteger(fence.epoch) || typeof fence.primaryId !== 'string' || typeof fence.instanceId !== 'string')
|
|
164
|
+
throw new TypeError('valid fencing token required');
|
|
165
|
+
const classification = fence.epoch === this.epoch && fence.primaryId === this.primary && fence.instanceId === this.instanceId ? 'current' : 'stale';
|
|
166
|
+
this.history.push(Object.freeze({ fence: Object.freeze({ ...fence }), value: structuredClone(value) }));
|
|
167
|
+
this.events.push(Object.freeze({ kind: 'primary-response', reason: `${classification} response retained in history` }));
|
|
168
|
+
return classification;
|
|
169
|
+
}
|
|
170
|
+
authorizeSideEffect(fence) {
|
|
171
|
+
return !!fence && Number.isSafeInteger(fence.epoch) && fence.epoch === this.epoch && fence.primaryId === this.primary && fence.instanceId === this.instanceId;
|
|
172
|
+
}
|
|
173
|
+
exhaustFallbacks(input) {
|
|
174
|
+
if (!input || !Array.isArray(input.unavailable) || !Array.isArray(input.coverage))
|
|
175
|
+
throw new TypeError('fallback results and coverage required');
|
|
176
|
+
if (this.exhaustedResult)
|
|
177
|
+
return this.exhaustedResult;
|
|
178
|
+
this.terminal = true;
|
|
179
|
+
const coverage = Object.freeze([...input.coverage]);
|
|
180
|
+
const outcome = coverage.length > 0 ? 'final' : 'needs-owner';
|
|
181
|
+
const reason = `reviewer timed out=${input.reviewerTimedOut}; unavailable fallbacks=${input.unavailable.length}; outcome=${outcome}`;
|
|
182
|
+
this.events.push(Object.freeze({ kind: 'fallbacks-exhausted', reason }));
|
|
183
|
+
this.exhaustedResult = Object.freeze({ terminal: true, outcome, coverage });
|
|
184
|
+
return this.exhaustedResult;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
function deepFreeze(value) { if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
188
|
+
Object.values(value).forEach((child) => deepFreeze(child));
|
|
189
|
+
Object.freeze(value);
|
|
190
|
+
} return value; }
|
|
191
|
+
//# sourceMappingURL=handover.js.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export interface NoProgressState {
|
|
2
|
+
readonly attemptCount: number;
|
|
3
|
+
readonly terminal: boolean;
|
|
4
|
+
readonly outcome: 'open' | 'final_with_coverage' | 'needs_owner';
|
|
5
|
+
readonly failureCounts: Readonly<Record<string, number>>;
|
|
6
|
+
readonly lastEvidenceFingerprint: string | null;
|
|
7
|
+
readonly rejectedIdeas: readonly string[];
|
|
8
|
+
readonly rejectedIdeaEvidence: Readonly<Record<string, string>>;
|
|
9
|
+
}
|
|
10
|
+
export type NoProgressEvent = {
|
|
11
|
+
readonly kind: 'primary';
|
|
12
|
+
readonly turn: number;
|
|
13
|
+
readonly asksForMore: boolean;
|
|
14
|
+
} | {
|
|
15
|
+
readonly kind: 'attempt';
|
|
16
|
+
readonly failure: string;
|
|
17
|
+
readonly evidenceFingerprint: string;
|
|
18
|
+
} | {
|
|
19
|
+
readonly kind: 'reviewer-timeout' | 'late-review' | 'fallback-unavailable';
|
|
20
|
+
readonly evidenceFingerprint: string;
|
|
21
|
+
} | {
|
|
22
|
+
readonly kind: 'rejected-idea';
|
|
23
|
+
readonly ideaFingerprint: string;
|
|
24
|
+
readonly evidenceFingerprint: string;
|
|
25
|
+
} | {
|
|
26
|
+
readonly kind: 'read-only-report';
|
|
27
|
+
readonly adequate: boolean;
|
|
28
|
+
readonly evidenceFingerprint: string;
|
|
29
|
+
} | {
|
|
30
|
+
readonly kind: 'disagreement';
|
|
31
|
+
readonly evidenceFingerprint: string;
|
|
32
|
+
};
|
|
33
|
+
export interface NoProgressOptions {
|
|
34
|
+
readonly loopLimit: number;
|
|
35
|
+
readonly taskAttemptBudget: number;
|
|
36
|
+
}
|
|
37
|
+
export interface NoProgressResult {
|
|
38
|
+
readonly state: NoProgressState;
|
|
39
|
+
readonly outcome: 'continue' | 'investigate' | 'not_requeued' | 'final_with_coverage' | 'needs_owner';
|
|
40
|
+
readonly progress: boolean;
|
|
41
|
+
}
|
|
42
|
+
export declare function initialNoProgressState(): NoProgressState;
|
|
43
|
+
/** Pure task-level attempt policy. It does not invoke providers or mutate shared decision history. */
|
|
44
|
+
export declare function evaluateNoProgress(state: NoProgressState, event: NoProgressEvent, options?: NoProgressOptions): NoProgressResult;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { normalizeProblemFingerprint } from './decision.js';
|
|
2
|
+
export function initialNoProgressState() {
|
|
3
|
+
return Object.freeze({ attemptCount: 0, terminal: false, outcome: 'open', failureCounts: Object.freeze({}), lastEvidenceFingerprint: null, rejectedIdeas: Object.freeze([]), rejectedIdeaEvidence: Object.freeze({}) });
|
|
4
|
+
}
|
|
5
|
+
/** Pure task-level attempt policy. It does not invoke providers or mutate shared decision history. */
|
|
6
|
+
export function evaluateNoProgress(state, event, options = { loopLimit: 2, taskAttemptBudget: 4 }) {
|
|
7
|
+
if (!validState(state) || !event || typeof event !== 'object' || !options || !Number.isSafeInteger(options.loopLimit) || options.loopLimit < 1 || !Number.isSafeInteger(options.taskAttemptBudget) || options.taskAttemptBudget < 1)
|
|
8
|
+
throw new TypeError('valid no-progress state, event, and positive budgets required');
|
|
9
|
+
if (state.terminal)
|
|
10
|
+
throw new Error('task policy is terminal');
|
|
11
|
+
const outcome = (nextState, result, progress) => Object.freeze({ state: nextState, outcome: result, progress });
|
|
12
|
+
if (event.kind === 'primary' && (!Number.isSafeInteger(event.turn) || event.turn < 1))
|
|
13
|
+
throw new TypeError('positive primary turn required');
|
|
14
|
+
if (event.kind === 'primary' && event.asksForMore && event.turn >= 2)
|
|
15
|
+
return outcome(terminalState(state, 'needs_owner'), 'needs_owner', false);
|
|
16
|
+
if (event.kind === 'read-only-report') {
|
|
17
|
+
requireFingerprint(event.evidenceFingerprint);
|
|
18
|
+
return event.adequate ? outcome(terminalState(state, 'final_with_coverage'), 'final_with_coverage', true) : recordAttempt(state, event.evidenceFingerprint, options, null, 'investigate');
|
|
19
|
+
}
|
|
20
|
+
if (event.kind === 'disagreement') {
|
|
21
|
+
requireFingerprint(event.evidenceFingerprint);
|
|
22
|
+
return recordAttempt(state, event.evidenceFingerprint, options, null, 'investigate');
|
|
23
|
+
}
|
|
24
|
+
if (event.kind === 'rejected-idea') {
|
|
25
|
+
requireFingerprint(event.ideaFingerprint);
|
|
26
|
+
requireFingerprint(event.evidenceFingerprint);
|
|
27
|
+
if (state.rejectedIdeas.includes(event.ideaFingerprint) && state.rejectedIdeaEvidence[event.ideaFingerprint] === event.evidenceFingerprint)
|
|
28
|
+
return outcome(state, 'not_requeued', false);
|
|
29
|
+
const next = Object.freeze({ ...state, rejectedIdeas: Object.freeze([...new Set([...state.rejectedIdeas, event.ideaFingerprint])]), rejectedIdeaEvidence: Object.freeze({ ...state.rejectedIdeaEvidence, [event.ideaFingerprint]: event.evidenceFingerprint }) });
|
|
30
|
+
return recordAttempt(next, event.evidenceFingerprint, options, null);
|
|
31
|
+
}
|
|
32
|
+
if (event.kind === 'late-review') {
|
|
33
|
+
requireFingerprint(event.evidenceFingerprint);
|
|
34
|
+
return recordAttempt(state, event.evidenceFingerprint, options, null, 'continue');
|
|
35
|
+
}
|
|
36
|
+
if (event.kind === 'primary')
|
|
37
|
+
return recordAttempt(state, state.lastEvidenceFingerprint ?? `primary-turn-${event.turn}`, options, null, 'continue');
|
|
38
|
+
const evidence = event.evidenceFingerprint;
|
|
39
|
+
requireFingerprint(evidence);
|
|
40
|
+
const failure = event.kind === 'attempt' ? normalizeProblemFingerprint(event.failure) : `reviewer ${event.kind}`;
|
|
41
|
+
if (!failure)
|
|
42
|
+
throw new TypeError('non-empty failure fingerprint required');
|
|
43
|
+
return recordAttempt(state, evidence, options, failure);
|
|
44
|
+
}
|
|
45
|
+
function recordAttempt(state, evidence, options, failure, underBudgetOutcome = 'continue') {
|
|
46
|
+
const progress = state.lastEvidenceFingerprint !== evidence;
|
|
47
|
+
const attemptCount = state.attemptCount + 1;
|
|
48
|
+
const counts = { ...state.failureCounts };
|
|
49
|
+
if (failure !== null)
|
|
50
|
+
counts[failure] = (counts[failure] ?? 0) + 1;
|
|
51
|
+
const next = Object.freeze({ ...state, attemptCount, lastEvidenceFingerprint: evidence, failureCounts: Object.freeze(counts) });
|
|
52
|
+
if (failure !== null && counts[failure] >= options.loopLimit || attemptCount >= options.taskAttemptBudget)
|
|
53
|
+
return Object.freeze({ state: terminalState(next, 'needs_owner'), outcome: 'needs_owner', progress });
|
|
54
|
+
return Object.freeze({ state: next, outcome: underBudgetOutcome, progress });
|
|
55
|
+
}
|
|
56
|
+
function terminalState(state, outcome) {
|
|
57
|
+
return Object.freeze({ ...state, terminal: true, outcome });
|
|
58
|
+
}
|
|
59
|
+
function requireFingerprint(value) { if (typeof value !== 'string' || !value.trim())
|
|
60
|
+
throw new TypeError('non-empty evidence fingerprint required'); }
|
|
61
|
+
function validState(state) {
|
|
62
|
+
return !!state && typeof state === 'object' && Number.isSafeInteger(state.attemptCount) && state.attemptCount >= 0 && typeof state.terminal === 'boolean' && (state.outcome === 'open' || state.outcome === 'final_with_coverage' || state.outcome === 'needs_owner') && !!state.failureCounts && typeof state.failureCounts === 'object' && Array.isArray(state.rejectedIdeas) && !!state.rejectedIdeaEvidence && typeof state.rejectedIdeaEvidence === 'object';
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=no-progress.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AdvisorBinding } from '../core/entities.js';
|
|
2
|
+
import { type AdvisorId } from '../core/ids.js';
|
|
3
|
+
/** In-memory registry of bound advisors and their deterministic failover order. */
|
|
4
|
+
export declare class PrimaryRegistry {
|
|
5
|
+
private readonly registered;
|
|
6
|
+
private orderedFallbacks;
|
|
7
|
+
private selected;
|
|
8
|
+
get bindings(): readonly AdvisorBinding[];
|
|
9
|
+
get primary(): AdvisorBinding | undefined;
|
|
10
|
+
get fallbackOrder(): readonly AdvisorId[];
|
|
11
|
+
register(binding: AdvisorBinding): AdvisorBinding;
|
|
12
|
+
selectPrimary(rawId: string): AdvisorBinding;
|
|
13
|
+
setFallbackOrder(rawIds: readonly string[]): readonly AdvisorBinding[];
|
|
14
|
+
nextFallback(): AdvisorBinding | undefined;
|
|
15
|
+
}
|