@ngockhoale/ckit 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +70 -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 +384 -0
- package/dist/src/cli/demo.d.ts +1 -0
- package/dist/src/cli/demo.js +30 -0
- package/dist/src/cli/lifecycle.d.ts +19 -0
- package/dist/src/cli/lifecycle.js +90 -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 +113 -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 +157 -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 +677 -0
- package/gui/index.html +51 -0
- package/gui/network.js +413 -0
- package/package.json +44 -4
- package/src/storage/schema.sql +42 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Versioned event envelope and minimal event union. Unknown schemas fail closed.
|
|
2
|
+
import { eventSeq, sessionId, taskId, projectId, runId, attemptId, eventId, decisionId, traceId, spanId, requirementId, artifactRef } from './ids.js';
|
|
3
|
+
export const EVENT_SCHEMA_VERSION = 1;
|
|
4
|
+
const ROLES = ['owner', 'advisor', 'worker', 'system'];
|
|
5
|
+
const UNKNOWN_REASONS = ['ack-lost', 'timeout', 'adapter-fault'];
|
|
6
|
+
const ISO_RE = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/;
|
|
7
|
+
function validIso8601(value) {
|
|
8
|
+
const m = ISO_RE.exec(value);
|
|
9
|
+
if (m === null)
|
|
10
|
+
return false;
|
|
11
|
+
const year = Number(m[1]), month = Number(m[2]), day = Number(m[3]), hour = Number(m[4]), minute = Number(m[5]), second = Number(m[6]);
|
|
12
|
+
if (month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year, month, 0)).getUTCDate() || hour > 23 || minute > 59 || second > 59)
|
|
13
|
+
return false;
|
|
14
|
+
const offset = m[8];
|
|
15
|
+
if (offset !== undefined && offset !== 'Z') {
|
|
16
|
+
const off = /^([+-])(\d{2}):(\d{2})$/.exec(offset);
|
|
17
|
+
if (off === null || Number(off[2]) > 23 || Number(off[3]) > 59)
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
function fail(msg) { throw new TypeError(`envelope rejected: ${msg}`); }
|
|
23
|
+
function typedNullable(field, parse, raw) { if (raw === null)
|
|
24
|
+
return null; if (typeof raw !== 'string' || raw.length === 0)
|
|
25
|
+
fail(`${field} must be a non-empty string or null`); return parse(raw); }
|
|
26
|
+
function isRecord(v) { return typeof v === 'object' && v !== null && !Array.isArray(v); }
|
|
27
|
+
export function validateEnvelope(raw) {
|
|
28
|
+
if (!isRecord(raw))
|
|
29
|
+
fail('not an object');
|
|
30
|
+
if (raw['schemaVersion'] !== EVENT_SCHEMA_VERSION)
|
|
31
|
+
fail(`unsupported schemaVersion ${JSON.stringify(raw['schemaVersion'])}`);
|
|
32
|
+
const seq = eventSeq(raw['seq']), sid = sessionId(raw['sessionId']), tid = taskId(raw['taskId']);
|
|
33
|
+
if (typeof raw['at'] !== 'string' || !validIso8601(raw['at']))
|
|
34
|
+
fail('at is not a valid ISO-8601 timestamp');
|
|
35
|
+
const causality = raw['causality'] === null ? null : eventSeq(raw['causality']);
|
|
36
|
+
if (!isRecord(raw['actor']))
|
|
37
|
+
fail('actor missing');
|
|
38
|
+
const role = raw['actor']['role'];
|
|
39
|
+
if (typeof role !== 'string' || !ROLES.includes(role))
|
|
40
|
+
fail(`unknown actor role ${JSON.stringify(role)}`);
|
|
41
|
+
const adapter = raw['actor']['adapter'];
|
|
42
|
+
if (adapter !== undefined && typeof adapter !== 'string')
|
|
43
|
+
fail('actor.adapter must be string');
|
|
44
|
+
const prov = raw['provenance'];
|
|
45
|
+
if (!isRecord(prov))
|
|
46
|
+
fail('provenance missing');
|
|
47
|
+
let provenance;
|
|
48
|
+
if (prov['source'] === 'simulated')
|
|
49
|
+
provenance = { source: 'simulated' };
|
|
50
|
+
else if (prov['source'] === 'live') {
|
|
51
|
+
if (typeof prov['ref'] !== 'string' || !prov['ref'])
|
|
52
|
+
fail('live provenance requires a non-empty ref');
|
|
53
|
+
provenance = { source: 'live', ref: prov['ref'] };
|
|
54
|
+
}
|
|
55
|
+
else
|
|
56
|
+
fail(`unknown provenance source ${JSON.stringify(prov['source'])}`);
|
|
57
|
+
const p = raw['payload'];
|
|
58
|
+
if (!isRecord(p))
|
|
59
|
+
fail('payload missing');
|
|
60
|
+
const payload = validatePayload(p);
|
|
61
|
+
const required = (key) => { if (!Object.hasOwn(raw, key))
|
|
62
|
+
fail(`${key} required`); return raw[key]; };
|
|
63
|
+
const stringField = (key, nullable = false) => { const value = required(key); if (nullable && value === null)
|
|
64
|
+
return null; if (typeof value !== 'string' || value.length === 0)
|
|
65
|
+
fail(`${key} must be a non-empty string${nullable ? ' or null' : ''}`); return value; };
|
|
66
|
+
const nullableId = (key) => stringField(key, true);
|
|
67
|
+
const artifacts = required('artifactRefs'), requirements = required('requirementIds');
|
|
68
|
+
if (!Array.isArray(artifacts) || !Array.isArray(requirements))
|
|
69
|
+
fail('reference arrays required');
|
|
70
|
+
const sessionSequence = eventSeq(required('sessionSequence'));
|
|
71
|
+
if (seq !== sessionSequence)
|
|
72
|
+
fail('seq and sessionSequence must agree');
|
|
73
|
+
const eventType = stringField('eventType');
|
|
74
|
+
if (eventType !== payload.type)
|
|
75
|
+
fail('eventType must match payload.type');
|
|
76
|
+
return Object.freeze({ schemaVersion: EVENT_SCHEMA_VERSION, seq, sessionId: sid, taskId: tid, at: raw['at'], causality,
|
|
77
|
+
eventId: eventId(stringField('eventId')), projectId: projectId(stringField('projectId')), runId: typedNullable('runId', runId, required('runId')), attemptId: typedNullable('attemptId', attemptId, required('attemptId')),
|
|
78
|
+
parentEventId: typedNullable('parentEventId', eventId, required('parentEventId')), causationId: typedNullable('causationId', eventId, required('causationId')), traceId: traceId(stringField('traceId')), spanId: spanId(stringField('spanId')),
|
|
79
|
+
sessionSequence, sourceAt: stringField('sourceAt', true), adapter: stringField('adapter', true), adapterVersion: stringField('adapterVersion', true),
|
|
80
|
+
eventType, status: stringField('status'), reasonCode: stringField('reasonCode', true),
|
|
81
|
+
artifactRefs: Object.freeze(artifacts.map((x) => artifactRef(typeof x === 'string' ? x : fail('invalid artifactRef')))),
|
|
82
|
+
decisionId: typedNullable('decisionId', decisionId, required('decisionId')), requirementIds: Object.freeze(requirements.map((x) => requirementId(typeof x === 'string' ? x : fail('invalid requirementId')))),
|
|
83
|
+
ckitVersion: stringField('ckitVersion'), policyVersion: stringField('policyVersion'), promptTemplateVersion: stringField('promptTemplateVersion'), redactedConfigHash: stringField('redactedConfigHash'),
|
|
84
|
+
actor: adapter === undefined ? { role: role } : { role: role, adapter }, provenance, payload });
|
|
85
|
+
}
|
|
86
|
+
function validatePayload(p) {
|
|
87
|
+
switch (p['type']) {
|
|
88
|
+
case 'TaskCreated':
|
|
89
|
+
if (typeof p['title'] !== 'string' || !p['title'])
|
|
90
|
+
fail('TaskCreated.title');
|
|
91
|
+
return { type: 'TaskCreated', title: p['title'] };
|
|
92
|
+
case 'AdvisorDispatched':
|
|
93
|
+
if (typeof p['promptRef'] !== 'string' || !p['promptRef'])
|
|
94
|
+
fail('AdvisorDispatched.promptRef');
|
|
95
|
+
if (typeof p['adapter'] !== 'string' || !p['adapter'])
|
|
96
|
+
fail('AdvisorDispatched.adapter');
|
|
97
|
+
return { type: 'AdvisorDispatched', promptRef: p['promptRef'], adapter: p['adapter'] };
|
|
98
|
+
case 'AdvisorAcked':
|
|
99
|
+
if (typeof p['adapter'] !== 'string' || !p['adapter'])
|
|
100
|
+
fail('AdvisorAcked.adapter');
|
|
101
|
+
return { type: 'AdvisorAcked', adapter: p['adapter'] };
|
|
102
|
+
case 'AdvisorCompleted':
|
|
103
|
+
if (typeof p['resultRef'] !== 'string' || !p['resultRef'])
|
|
104
|
+
fail('AdvisorCompleted.resultRef');
|
|
105
|
+
return { type: 'AdvisorCompleted', resultRef: p['resultRef'] };
|
|
106
|
+
case 'AdvisorUnknownOutcome':
|
|
107
|
+
if (typeof p['reason'] !== 'string' || !UNKNOWN_REASONS.includes(p['reason']))
|
|
108
|
+
fail('AdvisorUnknownOutcome.reason');
|
|
109
|
+
if (typeof p['note'] !== 'string')
|
|
110
|
+
fail('AdvisorUnknownOutcome.note');
|
|
111
|
+
return { type: 'AdvisorUnknownOutcome', reason: p['reason'], note: p['note'] };
|
|
112
|
+
case 'TaskCompleted':
|
|
113
|
+
if (p['outcome'] !== 'success' && p['outcome'] !== 'failed' && p['outcome'] !== 'unknown')
|
|
114
|
+
fail('TaskCompleted.outcome');
|
|
115
|
+
return { type: 'TaskCompleted', outcome: p['outcome'] };
|
|
116
|
+
case 'ReviewerSelected':
|
|
117
|
+
if (typeof p['reviewerId'] !== 'string' || !p['reviewerId'])
|
|
118
|
+
fail('ReviewerSelected.reviewerId');
|
|
119
|
+
if (!Number.isSafeInteger(p['evidenceRevision']) || p['evidenceRevision'] < 1)
|
|
120
|
+
fail('ReviewerSelected.evidenceRevision');
|
|
121
|
+
return { type: 'ReviewerSelected', reviewerId: p['reviewerId'], evidenceRevision: p['evidenceRevision'] };
|
|
122
|
+
default: fail(`unknown payload type ${JSON.stringify(p['type'])}`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
//# sourceMappingURL=events.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export type Brand<T, B extends string> = T & {
|
|
2
|
+
readonly __brand: B;
|
|
3
|
+
};
|
|
4
|
+
export type SessionId = Brand<string, 'SessionId'>;
|
|
5
|
+
export type TaskId = Brand<string, 'TaskId'>;
|
|
6
|
+
/** Per-session, gap-free, 1-based monotonic event sequence number. */
|
|
7
|
+
export type EventSeq = Brand<number, 'EventSeq'>;
|
|
8
|
+
export type ProjectId = Brand<string, 'ProjectId'>;
|
|
9
|
+
export type RunId = Brand<string, 'RunId'>;
|
|
10
|
+
export type AttemptId = Brand<string, 'AttemptId'>;
|
|
11
|
+
export type EventId = Brand<string, 'EventId'>;
|
|
12
|
+
export type DecisionId = Brand<string, 'DecisionId'>;
|
|
13
|
+
export type TraceId = Brand<string, 'TraceId'>;
|
|
14
|
+
export type SpanId = Brand<string, 'SpanId'>;
|
|
15
|
+
export type RequirementId = Brand<string, 'RequirementId'>;
|
|
16
|
+
export type ArtifactRef = Brand<string, 'ArtifactRef'>;
|
|
17
|
+
export type AdvisorId = Brand<string, 'AdvisorId'>;
|
|
18
|
+
export type AgentId = Brand<string, 'AgentId'>;
|
|
19
|
+
export type SourceId = Brand<string, 'SourceId'>;
|
|
20
|
+
export type IntentRevisionId = Brand<string, 'IntentRevisionId'>;
|
|
21
|
+
export type IdeaId = Brand<string, 'IdeaId'>;
|
|
22
|
+
export type AdvisorRequestId = Brand<string, 'AdvisorRequestId'>;
|
|
23
|
+
export type WorkOrderId = Brand<string, 'WorkOrderId'>;
|
|
24
|
+
export type AgentRunId = Brand<string, 'AgentRunId'>;
|
|
25
|
+
export type AuthorizationRef = Brand<string, 'AuthorizationRef'>;
|
|
26
|
+
export declare function sessionId(raw: string): SessionId;
|
|
27
|
+
export declare function taskId(raw: string): TaskId;
|
|
28
|
+
export declare function eventSeq(raw: number): EventSeq;
|
|
29
|
+
export declare const projectId: (raw: string) => ProjectId;
|
|
30
|
+
export declare const runId: (raw: string) => RunId;
|
|
31
|
+
export declare const attemptId: (raw: string) => AttemptId;
|
|
32
|
+
export declare const eventId: (raw: string) => EventId;
|
|
33
|
+
export declare const decisionId: (raw: string) => DecisionId;
|
|
34
|
+
export declare const traceId: (raw: string) => TraceId;
|
|
35
|
+
export declare const spanId: (raw: string) => SpanId;
|
|
36
|
+
export declare const requirementId: (raw: string) => RequirementId;
|
|
37
|
+
export declare const artifactRef: (raw: string) => ArtifactRef;
|
|
38
|
+
export declare const advisorId: (raw: string) => AdvisorId;
|
|
39
|
+
export declare const agentId: (raw: string) => AgentId;
|
|
40
|
+
export declare const sourceId: (raw: string) => SourceId;
|
|
41
|
+
export declare const intentRevisionId: (raw: string) => IntentRevisionId;
|
|
42
|
+
export declare const ideaId: (raw: string) => IdeaId;
|
|
43
|
+
export declare const advisorRequestId: (raw: string) => AdvisorRequestId;
|
|
44
|
+
export declare const workOrderId: (raw: string) => WorkOrderId;
|
|
45
|
+
export declare const agentRunId: (raw: string) => AgentRunId;
|
|
46
|
+
export declare const authorizationRef: (raw: string) => AuthorizationRef;
|
|
47
|
+
export declare const taskRevision: (raw: number) => number;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const SESSION_RE = /^session-[a-z0-9]{6,16}$/;
|
|
2
|
+
const TASK_RE = /^task-[a-z0-9]{6,16}$/;
|
|
3
|
+
const ENTITY_RE = /^[a-z][a-z0-9_-]{5,63}$/;
|
|
4
|
+
export function sessionId(raw) { if (!SESSION_RE.test(raw))
|
|
5
|
+
throw new TypeError(`invalid SessionId: ${JSON.stringify(raw)}`); return raw; }
|
|
6
|
+
export function taskId(raw) { if (!TASK_RE.test(raw))
|
|
7
|
+
throw new TypeError(`invalid TaskId: ${JSON.stringify(raw)}`); return raw; }
|
|
8
|
+
export function eventSeq(raw) { if (!Number.isSafeInteger(raw) || raw < 1)
|
|
9
|
+
throw new TypeError(`invalid EventSeq: ${String(raw)}`); return raw; }
|
|
10
|
+
function entityId(raw, brand) { if (!ENTITY_RE.test(raw))
|
|
11
|
+
throw new TypeError(`invalid ${brand}: ${JSON.stringify(raw)}`); return raw; }
|
|
12
|
+
export const projectId = (raw) => entityId(raw, 'ProjectId');
|
|
13
|
+
export const runId = (raw) => entityId(raw, 'RunId');
|
|
14
|
+
export const attemptId = (raw) => entityId(raw, 'AttemptId');
|
|
15
|
+
export const eventId = (raw) => entityId(raw, 'EventId');
|
|
16
|
+
export const decisionId = (raw) => entityId(raw, 'DecisionId');
|
|
17
|
+
export const traceId = (raw) => entityId(raw, 'TraceId');
|
|
18
|
+
export const spanId = (raw) => entityId(raw, 'SpanId');
|
|
19
|
+
export const requirementId = (raw) => entityId(raw, 'RequirementId');
|
|
20
|
+
export const artifactRef = (raw) => entityId(raw, 'ArtifactRef');
|
|
21
|
+
export const advisorId = (raw) => entityId(raw, 'AdvisorId');
|
|
22
|
+
export const agentId = (raw) => entityId(raw, 'AgentId');
|
|
23
|
+
export const sourceId = (raw) => entityId(raw, 'SourceId');
|
|
24
|
+
export const intentRevisionId = (raw) => entityId(raw, 'IntentRevisionId');
|
|
25
|
+
export const ideaId = (raw) => entityId(raw, 'IdeaId');
|
|
26
|
+
export const advisorRequestId = (raw) => entityId(raw, 'AdvisorRequestId');
|
|
27
|
+
export const workOrderId = (raw) => entityId(raw, 'WorkOrderId');
|
|
28
|
+
export const agentRunId = (raw) => entityId(raw, 'AgentRunId');
|
|
29
|
+
export const authorizationRef = (raw) => entityId(raw, 'AuthorizationRef');
|
|
30
|
+
export const taskRevision = (raw) => { if (!Number.isSafeInteger(raw) || raw < 1)
|
|
31
|
+
throw new TypeError(`invalid TaskRevision: ${String(raw)}`); return raw; };
|
|
32
|
+
//# sourceMappingURL=ids.js.map
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { Envelope } from './events.js';
|
|
2
|
+
import type { EventSeq } from './ids.js';
|
|
3
|
+
import { type DecisionBudget } from './policy.js';
|
|
4
|
+
import type { AgentRunStatus } from './entities.js';
|
|
5
|
+
export interface AgentState {
|
|
6
|
+
readonly runId: string;
|
|
7
|
+
readonly state: AgentRunStatus;
|
|
8
|
+
}
|
|
9
|
+
export interface RequestState {
|
|
10
|
+
readonly requestId: string;
|
|
11
|
+
readonly delivery: 'prepared' | 'sent' | 'unknown' | 'failed';
|
|
12
|
+
readonly slot: number | null;
|
|
13
|
+
readonly outcome: 'pending' | 'partial' | 'done' | 'unknown';
|
|
14
|
+
}
|
|
15
|
+
export interface OrchestrationState {
|
|
16
|
+
readonly session: SessionState;
|
|
17
|
+
readonly agents: readonly AgentState[];
|
|
18
|
+
readonly requests: readonly RequestState[];
|
|
19
|
+
readonly budget: DecisionBudget | null;
|
|
20
|
+
readonly paused: boolean;
|
|
21
|
+
}
|
|
22
|
+
export declare function initialOrchestration(sessionId: Envelope['sessionId'], budget?: DecisionBudget | null): OrchestrationState;
|
|
23
|
+
/** Pause gates future work; it never fabricates a stopped/interrupted agent state. */
|
|
24
|
+
export declare function pauseOrchestration(state: OrchestrationState): OrchestrationState;
|
|
25
|
+
export declare function canDispatchAgent(state: OrchestrationState, agentState: AgentRunStatus): boolean;
|
|
26
|
+
export declare function recordAgentTurnResult(state: OrchestrationState, runId: string, result: 'partial' | 'done' | 'failed'): OrchestrationState;
|
|
27
|
+
export declare function validateEventReferences(events: readonly Envelope[]): void;
|
|
28
|
+
export type SessionPhase = 'empty' | 'taskActive' | 'awaitingAdvisor' | 'needsReconciliation' | 'closed';
|
|
29
|
+
export interface TaskView {
|
|
30
|
+
readonly id: Envelope['taskId'];
|
|
31
|
+
readonly title: string;
|
|
32
|
+
}
|
|
33
|
+
export interface SessionState {
|
|
34
|
+
readonly sessionId: Envelope['sessionId'];
|
|
35
|
+
readonly phase: SessionPhase;
|
|
36
|
+
readonly task: TaskView | null;
|
|
37
|
+
/** Last applied seq; 0 when empty. Monotonic, gap-free. */
|
|
38
|
+
readonly lastSeq: EventSeq;
|
|
39
|
+
/** Terminal result of the task, when the session closed. */
|
|
40
|
+
readonly outcome: 'success' | 'failed' | 'unknown' | null;
|
|
41
|
+
}
|
|
42
|
+
export declare class TransitionError extends Error {
|
|
43
|
+
readonly from: SessionPhase;
|
|
44
|
+
readonly eventType: string;
|
|
45
|
+
constructor(message: string, from: SessionPhase, eventType: string);
|
|
46
|
+
}
|
|
47
|
+
export declare function initialSession(sessionId: Envelope['sessionId']): SessionState;
|
|
48
|
+
/**
|
|
49
|
+
* Apply one already-validated envelope to the session state.
|
|
50
|
+
* Sequence must be exactly lastSeq+1 (gap-free); the session id and task id must match.
|
|
51
|
+
* Throws {@link TransitionError} on any rule violation; the caller's state is never mutated.
|
|
52
|
+
*/
|
|
53
|
+
export declare function reduce(state: SessionState, env: Envelope): SessionState;
|
|
54
|
+
/** Fold a validated event list over the initial state — replay for determinism checks. */
|
|
55
|
+
export declare function replay(sessionId: Envelope['sessionId'], events: readonly Envelope[]): SessionState;
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { canDispatch } from './policy.js';
|
|
2
|
+
export function initialOrchestration(sessionId, budget = null) {
|
|
3
|
+
return Object.freeze({ session: initialSession(sessionId), agents: Object.freeze([]), requests: Object.freeze([]), budget, paused: false });
|
|
4
|
+
}
|
|
5
|
+
/** Pause gates future work; it never fabricates a stopped/interrupted agent state. */
|
|
6
|
+
export function pauseOrchestration(state) {
|
|
7
|
+
return Object.freeze({ ...state, paused: true });
|
|
8
|
+
}
|
|
9
|
+
export function canDispatchAgent(state, agentState) {
|
|
10
|
+
return canDispatch({ paused: state.paused, agentState });
|
|
11
|
+
}
|
|
12
|
+
export function recordAgentTurnResult(state, runId, result) {
|
|
13
|
+
if (!runId)
|
|
14
|
+
throw new TypeError('runId required');
|
|
15
|
+
const agents = state.agents.map(agent => agent.runId === runId ? Object.freeze({ ...agent, state: result === 'failed' ? 'failed' : 'idle' }) : agent);
|
|
16
|
+
const requests = state.requests.map(request => request.requestId === runId ? Object.freeze({ ...request, outcome: result === 'failed' ? 'unknown' : result }) : request);
|
|
17
|
+
return Object.freeze({ ...state, agents: Object.freeze(agents), requests: Object.freeze(requests) });
|
|
18
|
+
} /* an agent/tool turn result does not complete the task/session */
|
|
19
|
+
export function validateEventReferences(events) {
|
|
20
|
+
const ids = new Set(events.map(event => event.eventId));
|
|
21
|
+
for (const event of events) {
|
|
22
|
+
if (event.parentEventId !== null && !ids.has(event.parentEventId))
|
|
23
|
+
throw new TransitionError('parentEventId reference missing', 'empty', event.payload.type);
|
|
24
|
+
if (event.causationId !== null && !ids.has(event.causationId))
|
|
25
|
+
throw new TransitionError('causationId reference missing', 'empty', event.payload.type);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export class TransitionError extends Error {
|
|
29
|
+
from;
|
|
30
|
+
eventType;
|
|
31
|
+
constructor(message, from, eventType) {
|
|
32
|
+
super(`${message} (from=${from}, event=${eventType})`);
|
|
33
|
+
this.from = from;
|
|
34
|
+
this.eventType = eventType;
|
|
35
|
+
this.name = 'TransitionError';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export function initialSession(sessionId) {
|
|
39
|
+
return { sessionId, phase: 'empty', task: null, lastSeq: 0, outcome: null };
|
|
40
|
+
}
|
|
41
|
+
function must(cond, message, from, eventType) {
|
|
42
|
+
if (!cond)
|
|
43
|
+
throw new TransitionError(message, from, eventType);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Apply one already-validated envelope to the session state.
|
|
47
|
+
* Sequence must be exactly lastSeq+1 (gap-free); the session id and task id must match.
|
|
48
|
+
* Throws {@link TransitionError} on any rule violation; the caller's state is never mutated.
|
|
49
|
+
*/
|
|
50
|
+
export function reduce(state, env) {
|
|
51
|
+
must(env.seq === state.lastSeq + 1, 'seq must be lastSeq+1', state.phase, env.payload.type);
|
|
52
|
+
must(env.sessionId === state.sessionId, 'sessionId mismatch', state.phase, env.payload.type);
|
|
53
|
+
if (state.task !== null) {
|
|
54
|
+
must(env.taskId === state.task.id, 'taskId mismatch', state.phase, env.payload.type);
|
|
55
|
+
}
|
|
56
|
+
const next = applyPayload(state, env);
|
|
57
|
+
return { ...next, lastSeq: env.seq };
|
|
58
|
+
}
|
|
59
|
+
function applyPayload(s, env) {
|
|
60
|
+
const t = env.payload.type;
|
|
61
|
+
switch (s.phase) {
|
|
62
|
+
case 'empty': {
|
|
63
|
+
must(t === 'TaskCreated', `phase empty only accepts TaskCreated`, s.phase, t);
|
|
64
|
+
const p = env.payload;
|
|
65
|
+
if (p.type !== 'TaskCreated')
|
|
66
|
+
throw new TransitionError('unreachable', s.phase, t);
|
|
67
|
+
return { sessionId: s.sessionId, phase: 'taskActive', task: { id: env.taskId, title: p.title }, lastSeq: s.lastSeq, outcome: null };
|
|
68
|
+
}
|
|
69
|
+
case 'taskActive': {
|
|
70
|
+
must(t === 'AdvisorDispatched' || t === 'TaskCompleted', 'taskActive accepts AdvisorDispatched or TaskCompleted', s.phase, t);
|
|
71
|
+
if (t === 'AdvisorDispatched') {
|
|
72
|
+
return { ...s, phase: 'awaitingAdvisor' };
|
|
73
|
+
}
|
|
74
|
+
const p = env.payload;
|
|
75
|
+
if (p.type !== 'TaskCompleted')
|
|
76
|
+
throw new TransitionError('unreachable', s.phase, t);
|
|
77
|
+
must(p.outcome !== 'unknown', 'close with unknown outcome requires needsReconciliation', s.phase, t);
|
|
78
|
+
return { ...s, phase: 'closed', outcome: p.outcome };
|
|
79
|
+
}
|
|
80
|
+
case 'awaitingAdvisor': {
|
|
81
|
+
must(t === 'AdvisorAcked' || t === 'AdvisorCompleted' || t === 'AdvisorUnknownOutcome', 'awaitingAdvisor accepts advisor lifecycle events only', s.phase, t);
|
|
82
|
+
if (t === 'AdvisorAcked') {
|
|
83
|
+
// Ack is transport-level only: the session keeps waiting; it is NOT completion.
|
|
84
|
+
return { ...s };
|
|
85
|
+
}
|
|
86
|
+
if (t === 'AdvisorCompleted') {
|
|
87
|
+
return { ...s, phase: 'taskActive' };
|
|
88
|
+
}
|
|
89
|
+
return { ...s, phase: 'needsReconciliation' };
|
|
90
|
+
}
|
|
91
|
+
case 'needsReconciliation': {
|
|
92
|
+
// Fail closed: no new dispatch from here (prevents blind resend); owner/core reconciles, then closes.
|
|
93
|
+
must(t === 'TaskCompleted' && env.payload.type === 'TaskCompleted', 'needsReconciliation accepts only TaskCompleted after reconciliation', s.phase, t);
|
|
94
|
+
const p = env.payload;
|
|
95
|
+
if (p.type !== 'TaskCompleted')
|
|
96
|
+
throw new TransitionError('unreachable', s.phase, t);
|
|
97
|
+
must(p.outcome !== 'success', 'success cannot be claimed from an unverified outcome', s.phase, t);
|
|
98
|
+
return { ...s, phase: 'closed', outcome: p.outcome };
|
|
99
|
+
}
|
|
100
|
+
case 'closed': {
|
|
101
|
+
throw new TransitionError('session is closed; no further events accepted', s.phase, t);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/** Fold a validated event list over the initial state — replay for determinism checks. */
|
|
106
|
+
export function replay(sessionId, events) {
|
|
107
|
+
validateEventReferences(events);
|
|
108
|
+
return events.reduce(reduce, initialSession(sessionId));
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=machine.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { AgentRunStatus } from './entities.js';
|
|
2
|
+
export interface PrimaryAuthority {
|
|
3
|
+
readonly epoch: number;
|
|
4
|
+
readonly primaryId: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function advanceEpoch(current: PrimaryAuthority, primaryId: string): PrimaryAuthority;
|
|
7
|
+
export declare function selectPrimaryResponse(current: PrimaryAuthority, responseEpoch: number, responderId: string): 'current' | 'stale';
|
|
8
|
+
export type SlotStatus = 'reserved' | 'consumed' | 'needsReconciliation' | 'released';
|
|
9
|
+
export interface BudgetSlot {
|
|
10
|
+
readonly requestId: string;
|
|
11
|
+
readonly status: SlotStatus;
|
|
12
|
+
}
|
|
13
|
+
export interface ReviewerSlot {
|
|
14
|
+
readonly requestId: string;
|
|
15
|
+
readonly reviewerId: string;
|
|
16
|
+
readonly evidenceRevision: number;
|
|
17
|
+
readonly status: 'sent' | 'needsReconciliation';
|
|
18
|
+
}
|
|
19
|
+
export interface DecisionBudget {
|
|
20
|
+
readonly decisionId: string;
|
|
21
|
+
readonly primary: readonly BudgetSlot[];
|
|
22
|
+
readonly reviewers: readonly ReviewerSlot[];
|
|
23
|
+
readonly outcome: 'open' | 'needs_owner';
|
|
24
|
+
}
|
|
25
|
+
export declare function createDecisionBudget(decisionId: string): DecisionBudget;
|
|
26
|
+
export declare function reservePrimary(budget: DecisionBudget, requestId: string): DecisionBudget;
|
|
27
|
+
export declare function settlePrimary(budget: DecisionBudget, requestId: string, result: 'sent' | 'unknown' | 'failedBeforeSend'): DecisionBudget;
|
|
28
|
+
export declare function reserveReviewer(budget: DecisionBudget, requestId: string, reviewerId: string, evidenceRevision: number, maxReviewers?: number): DecisionBudget;
|
|
29
|
+
export declare function canDispatch(input: {
|
|
30
|
+
readonly paused: boolean;
|
|
31
|
+
readonly agentState: AgentRunStatus;
|
|
32
|
+
}): boolean;
|
|
33
|
+
export declare function pausedAgentState(state: AgentRunStatus, paused: boolean): AgentRunStatus;
|
|
34
|
+
export declare function nextPrimaryOutcome(budget: DecisionBudget, proposed: string): 'needs_owner' | 'final' | 'continue';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export function advanceEpoch(current, primaryId) {
|
|
2
|
+
if (!primaryId)
|
|
3
|
+
throw new TypeError('primaryId required');
|
|
4
|
+
return Object.freeze({ epoch: current.epoch + 1, primaryId });
|
|
5
|
+
}
|
|
6
|
+
export function selectPrimaryResponse(current, responseEpoch, responderId) {
|
|
7
|
+
return current.epoch === responseEpoch && current.primaryId === responderId ? 'current' : 'stale';
|
|
8
|
+
}
|
|
9
|
+
export function createDecisionBudget(decisionId) {
|
|
10
|
+
if (!decisionId)
|
|
11
|
+
throw new TypeError('decisionId required');
|
|
12
|
+
return Object.freeze({ decisionId, primary: Object.freeze([]), reviewers: Object.freeze([]), outcome: 'open' });
|
|
13
|
+
}
|
|
14
|
+
export function reservePrimary(budget, requestId) {
|
|
15
|
+
if (!requestId)
|
|
16
|
+
throw new TypeError('requestId required');
|
|
17
|
+
if (budget.primary.some(slot => slot.requestId === requestId))
|
|
18
|
+
return budget;
|
|
19
|
+
const releasedIndex = budget.primary.findIndex(slot => slot.status === 'released');
|
|
20
|
+
if ((budget.outcome !== 'open' && releasedIndex < 0) || (releasedIndex < 0 && budget.primary.length >= 2)) {
|
|
21
|
+
return Object.freeze({ ...budget, outcome: 'needs_owner' });
|
|
22
|
+
}
|
|
23
|
+
const replacement = Object.freeze({ requestId, status: 'reserved' });
|
|
24
|
+
const primary = [...budget.primary];
|
|
25
|
+
if (releasedIndex >= 0)
|
|
26
|
+
primary[releasedIndex] = replacement;
|
|
27
|
+
else
|
|
28
|
+
primary.push(replacement);
|
|
29
|
+
return Object.freeze({ ...budget, primary: Object.freeze(primary), outcome: 'open' });
|
|
30
|
+
}
|
|
31
|
+
export function settlePrimary(budget, requestId, result) {
|
|
32
|
+
const slot = budget.primary.find(s => s.requestId === requestId);
|
|
33
|
+
if (!slot || slot.status !== 'reserved')
|
|
34
|
+
throw new TypeError('primary request is not reserved');
|
|
35
|
+
const status = result === 'failedBeforeSend' ? 'released' : result === 'unknown' ? 'needsReconciliation' : 'consumed';
|
|
36
|
+
return Object.freeze({ ...budget, primary: Object.freeze(budget.primary.map(s => s === slot ? Object.freeze({ ...s, status }) : s)) });
|
|
37
|
+
}
|
|
38
|
+
export function reserveReviewer(budget, requestId, reviewerId, evidenceRevision, maxReviewers = 2) {
|
|
39
|
+
if (!requestId || !reviewerId || !Number.isSafeInteger(evidenceRevision) || evidenceRevision < 1)
|
|
40
|
+
throw new TypeError('invalid reviewer request');
|
|
41
|
+
if (budget.reviewers.some(s => s.requestId === requestId))
|
|
42
|
+
return budget;
|
|
43
|
+
if (budget.reviewers.length >= maxReviewers || budget.reviewers.some(s => s.reviewerId === reviewerId))
|
|
44
|
+
throw new TypeError('reviewer budget exceeded');
|
|
45
|
+
return Object.freeze({ ...budget, reviewers: Object.freeze([...budget.reviewers, Object.freeze({ requestId, reviewerId, evidenceRevision, status: 'sent' })]) });
|
|
46
|
+
}
|
|
47
|
+
export function canDispatch(input) {
|
|
48
|
+
return !input.paused && (input.agentState === 'not_started' || input.agentState === 'idle');
|
|
49
|
+
}
|
|
50
|
+
export function pausedAgentState(state, paused) {
|
|
51
|
+
// Pause is a dispatch gate, not a claim that a running process stopped.
|
|
52
|
+
return state;
|
|
53
|
+
}
|
|
54
|
+
export function nextPrimaryOutcome(budget, proposed) {
|
|
55
|
+
if (budget.primary.filter(s => s.status !== 'released').length >= 2 && proposed !== 'done' && proposed !== 'execute')
|
|
56
|
+
return 'needs_owner';
|
|
57
|
+
return budget.primary.length >= 2 ? 'final' : 'continue';
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=policy.js.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { SourceRole } from './entities.js';
|
|
2
|
+
export type MessageOrigin = 'ckit' | 'web' | 'repository' | 'agent' | 'unknown';
|
|
3
|
+
export interface IncomingSourceMessage {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly origin: MessageOrigin;
|
|
6
|
+
readonly role: string;
|
|
7
|
+
readonly text: string;
|
|
8
|
+
readonly transportActor: 'owner' | 'advisor' | 'worker' | 'system';
|
|
9
|
+
}
|
|
10
|
+
export interface ClassifiedSourceMessage {
|
|
11
|
+
readonly id: string;
|
|
12
|
+
readonly origin: MessageOrigin;
|
|
13
|
+
readonly role: SourceRole;
|
|
14
|
+
readonly text: string;
|
|
15
|
+
readonly transportActor: IncomingSourceMessage['transportActor'];
|
|
16
|
+
readonly authoritySource: 'transport';
|
|
17
|
+
}
|
|
18
|
+
export declare function classifySourceMessage(message: IncomingSourceMessage): ClassifiedSourceMessage;
|
|
19
|
+
export declare function promoteRequirement(message: IncomingSourceMessage, actingActor: 'owner' | 'advisor' | 'worker' | 'system'): ClassifiedSourceMessage;
|
|
20
|
+
export declare function isOutboundEcho(message: IncomingSourceMessage, controllerRequestIds: readonly string[]): boolean;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { DomainValidationError } from './errors.js';
|
|
2
|
+
export function classifySourceMessage(message) {
|
|
3
|
+
if (!message || typeof message.id !== 'string' || !message.id || typeof message.text !== 'string' || !['ckit', 'web', 'repository', 'agent', 'unknown'].includes(message.origin)) {
|
|
4
|
+
throw new DomainValidationError('ENVELOPE_INVALID', 'source message is malformed');
|
|
5
|
+
}
|
|
6
|
+
const assigned = message.transportActor === 'owner' ? 'owner' : message.transportActor;
|
|
7
|
+
// Claim text is preserved as data; it is never interpreted as authority.
|
|
8
|
+
return { id: message.id, origin: message.origin, role: assigned, text: message.text, transportActor: message.transportActor, authoritySource: 'transport' };
|
|
9
|
+
}
|
|
10
|
+
export function promoteRequirement(message, actingActor) {
|
|
11
|
+
const classified = classifySourceMessage(message);
|
|
12
|
+
if (message.origin !== 'ckit' || message.transportActor !== 'owner' || actingActor !== 'owner') {
|
|
13
|
+
const code = message.role === 'owner' || message.role === 'system' || /"(?:role|policy|command)"\s*:/.test(message.text) ? 'FORGED_AUTHORITY' : 'OWNER_TRANSPORT_REQUIRED';
|
|
14
|
+
throw new DomainValidationError(code, 'requirement promotion requires owner-authenticated transport context');
|
|
15
|
+
}
|
|
16
|
+
return classified;
|
|
17
|
+
}
|
|
18
|
+
export function isOutboundEcho(message, controllerRequestIds) {
|
|
19
|
+
return message.origin === 'web' && message.transportActor !== 'owner' && controllerRequestIds.includes(message.id);
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=provenance.js.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type Actor, type CkitEventPayload, type Envelope } from './events.js';
|
|
2
|
+
import type { ProjectId, SessionId, TaskId } from './ids.js';
|
|
3
|
+
export interface EventStep {
|
|
4
|
+
readonly payload: CkitEventPayload;
|
|
5
|
+
readonly actor: Actor;
|
|
6
|
+
readonly status?: string;
|
|
7
|
+
readonly reasonCode?: string | null;
|
|
8
|
+
readonly decision?: {
|
|
9
|
+
readonly decisionId?: string;
|
|
10
|
+
readonly reasonCode: string;
|
|
11
|
+
};
|
|
12
|
+
readonly runId?: string | null;
|
|
13
|
+
readonly attemptId?: string | null;
|
|
14
|
+
readonly adapter?: string | null;
|
|
15
|
+
readonly adapterVersion?: string | null;
|
|
16
|
+
readonly sourceAt?: string | null;
|
|
17
|
+
readonly requirementIds?: readonly string[];
|
|
18
|
+
readonly artifactRefs?: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
export interface RecordingContext {
|
|
21
|
+
readonly sessionId: SessionId;
|
|
22
|
+
readonly taskId: TaskId;
|
|
23
|
+
readonly projectId: ProjectId;
|
|
24
|
+
readonly at: () => string;
|
|
25
|
+
readonly source: 'simulated' | {
|
|
26
|
+
readonly liveRef: string;
|
|
27
|
+
};
|
|
28
|
+
readonly ckitVersion?: string;
|
|
29
|
+
readonly policyVersion?: string;
|
|
30
|
+
readonly promptTemplateVersion?: string;
|
|
31
|
+
readonly redactedConfigHash?: string;
|
|
32
|
+
readonly traceId?: string;
|
|
33
|
+
}
|
|
34
|
+
export declare function recordEvent(context: RecordingContext, step: EventStep, previous?: Envelope): Envelope;
|
|
35
|
+
export declare function recordSteps(context: RecordingContext, steps: readonly EventStep[]): readonly Envelope[];
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Event recording seam: every flow step becomes a fail-closed §6.1 envelope.
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { EVENT_SCHEMA_VERSION, validateEnvelope } from './events.js';
|
|
4
|
+
import { attemptId, decisionId, eventId, eventSeq, projectId, runId, sessionId, spanId, taskId, traceId } from './ids.js';
|
|
5
|
+
import { containsSecretText } from '../security/redact.js';
|
|
6
|
+
const sessionSuffix = (session, length) => createHash('sha256').update(session.replace(/[^a-z0-9_-]/g, '')).digest('hex').slice(0, length);
|
|
7
|
+
const eventIdFor = (session, sequence) => eventId(`event-${sessionSuffix(session, 10)}-${String(sequence).padStart(6, '0')}`);
|
|
8
|
+
const spanIdFor = (session, sequence) => spanId(`span-${sessionSuffix(session, 10)}-${String(sequence).padStart(6, '0')}`);
|
|
9
|
+
const traceIdFor = (session) => traceId(`trace-${sessionSuffix(session, 12)}`);
|
|
10
|
+
const SECRET_VALUE = { test: containsSecretText };
|
|
11
|
+
function assertNoSecrets(value) {
|
|
12
|
+
if (typeof value === 'string' && SECRET_VALUE.test(value))
|
|
13
|
+
throw new TypeError('sensitive event content rejected');
|
|
14
|
+
if (Array.isArray(value)) {
|
|
15
|
+
for (const item of value)
|
|
16
|
+
assertNoSecrets(item);
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
if (typeof value === 'object' && value !== null)
|
|
20
|
+
for (const item of Object.values(value))
|
|
21
|
+
assertNoSecrets(item);
|
|
22
|
+
}
|
|
23
|
+
const safeMetadata = (value) => {
|
|
24
|
+
if (value == null)
|
|
25
|
+
return null;
|
|
26
|
+
if (SECRET_VALUE.test(value))
|
|
27
|
+
throw new TypeError('sensitive metadata rejected');
|
|
28
|
+
return value;
|
|
29
|
+
};
|
|
30
|
+
export function recordEvent(context, step, previous) {
|
|
31
|
+
if (previous !== undefined && (previous.sessionId !== context.sessionId || previous.taskId !== context.taskId || previous.projectId !== context.projectId)) {
|
|
32
|
+
throw new TypeError('previous event belongs to a different project/session/task');
|
|
33
|
+
}
|
|
34
|
+
const seq = eventSeq((previous?.seq ?? 0) + 1);
|
|
35
|
+
const event = eventIdFor(context.sessionId, seq);
|
|
36
|
+
assertNoSecrets(step.payload);
|
|
37
|
+
assertNoSecrets(step.actor);
|
|
38
|
+
const reasonCode = step.decision?.reasonCode ?? step.reasonCode ?? null;
|
|
39
|
+
assertNoSecrets(reasonCode);
|
|
40
|
+
assertNoSecrets(context.source === 'simulated' ? null : context.source.liveRef);
|
|
41
|
+
assertNoSecrets(context.redactedConfigHash);
|
|
42
|
+
assertNoSecrets(step.adapter);
|
|
43
|
+
assertNoSecrets(step.adapterVersion);
|
|
44
|
+
if (reasonCode !== null && reasonCode.trim().length === 0)
|
|
45
|
+
throw new TypeError('reasonCode must be non-empty or null');
|
|
46
|
+
const provenance = context.source === 'simulated' ? { source: 'simulated' } : { source: 'live', ref: safeMetadata(context.source.liveRef) ?? '' };
|
|
47
|
+
const candidate = {
|
|
48
|
+
schemaVersion: EVENT_SCHEMA_VERSION, seq, sessionSequence: seq, sessionId: context.sessionId, taskId: context.taskId,
|
|
49
|
+
projectId: context.projectId, at: context.at(), sourceAt: step.sourceAt ?? null, causality: previous?.seq ?? null,
|
|
50
|
+
eventId: event, parentEventId: previous?.eventId ?? null, causationId: previous?.eventId ?? null,
|
|
51
|
+
runId: step.runId == null ? null : runId(step.runId), attemptId: step.attemptId == null ? null : attemptId(step.attemptId),
|
|
52
|
+
traceId: context.traceId === undefined ? traceIdFor(context.sessionId) : traceId(context.traceId), spanId: spanIdFor(context.sessionId, seq),
|
|
53
|
+
actor: step.actor, provenance, adapter: safeMetadata(step.adapter), adapterVersion: safeMetadata(step.adapterVersion),
|
|
54
|
+
eventType: step.payload.type, status: safeMetadata(step.status) ?? 'recorded', reasonCode: safeMetadata(reasonCode),
|
|
55
|
+
artifactRefs: step.artifactRefs ?? [], decisionId: step.decision?.decisionId == null ? null : decisionId(step.decision.decisionId),
|
|
56
|
+
requirementIds: step.requirementIds ?? [], ckitVersion: context.ckitVersion ?? '0.0.0', policyVersion: context.policyVersion ?? '1',
|
|
57
|
+
promptTemplateVersion: context.promptTemplateVersion ?? '1', redactedConfigHash: safeMetadata(context.redactedConfigHash) ?? 'unavailable', payload: step.payload,
|
|
58
|
+
};
|
|
59
|
+
return validateEnvelope(candidate);
|
|
60
|
+
}
|
|
61
|
+
export function recordSteps(context, steps) {
|
|
62
|
+
const result = [];
|
|
63
|
+
for (const step of steps)
|
|
64
|
+
result.push(recordEvent(context, step, result.at(-1)));
|
|
65
|
+
return Object.freeze(result);
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=record.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Envelope } from './events.js';
|
|
2
|
+
import type { ProjectId, SessionId } from './ids.js';
|
|
3
|
+
import { type SessionState } from './machine.js';
|
|
4
|
+
export interface SessionProjection extends SessionState {
|
|
5
|
+
readonly projectId: ProjectId | null;
|
|
6
|
+
}
|
|
7
|
+
/** Pure, read-only projection: groups by session identity and never emits effects. */
|
|
8
|
+
export declare function initialProjection(session: SessionId): SessionProjection;
|
|
9
|
+
export declare function projectSession(session: SessionId, events: readonly Envelope[]): SessionProjection;
|
|
10
|
+
export declare function projectEvents(events: readonly Envelope[]): ReadonlyMap<SessionId, SessionProjection>;
|