@indigoai-us/hq-cli 5.345.214 → 5.345.215
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/CHANGELOG.md +93 -0
- package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
- package/dist/command-catalog.generated.d.ts +180 -13
- package/dist/command-catalog.generated.js +221 -13
- package/dist/commands/agents.d.ts +51 -1
- package/dist/commands/agents.js +154 -2
- package/dist/commands/bot-jobs.d.ts +2 -15
- package/dist/commands/bot-jobs.js +2 -94
- package/dist/commands/bot-runtime.d.ts +46 -5
- package/dist/commands/bot-runtime.js +228 -18
- package/dist/commands/bot.d.ts +16 -9
- package/dist/commands/bot.js +231 -55
- package/dist/commands/capacity.d.ts +4 -1
- package/dist/commands/capacity.js +46 -10
- package/dist/commands/cloud.d.ts +66 -13
- package/dist/commands/cloud.js +121 -40
- package/dist/commands/company-restore.d.ts +23 -0
- package/dist/commands/company-restore.js +128 -0
- package/dist/commands/company.js +2 -0
- package/dist/commands/core-delegate-w1b.js +15 -1
- package/dist/commands/core-policy.js +67 -8
- package/dist/commands/daemon.js +5 -0
- package/dist/commands/files-browse.d.ts +11 -4
- package/dist/commands/files-browse.js +21 -4
- package/dist/commands/files.d.ts +1 -1
- package/dist/commands/files.js +25 -11
- package/dist/commands/integrations-auth-rules.d.ts +27 -0
- package/dist/commands/integrations-auth-rules.js +79 -0
- package/dist/commands/integrations-connect.d.ts +10 -3
- package/dist/commands/integrations-connect.js +87 -13
- package/dist/commands/integrations-import.js +124 -12
- package/dist/commands/lanes.js +28 -11
- package/dist/commands/mesh.d.ts +2 -0
- package/dist/commands/mesh.js +60 -35
- package/dist/commands/sources.js +6 -0
- package/dist/commands/storage-offload.d.ts +12 -0
- package/dist/commands/storage-offload.js +41 -3
- package/dist/commands/sync-held.js +5 -2
- package/dist/commands/sync-mode.js +5 -0
- package/dist/commands/whoami.js +4 -0
- package/dist/lazy-commands.js +3 -5
- package/dist/lib/bot/config.d.ts +1 -0
- package/dist/lib/bot/config.js +10 -0
- package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
- package/dist/lib/bot/eventbridge-cron.js +104 -0
- package/dist/lib/bot/fleet-cron.d.ts +8 -0
- package/dist/lib/bot/fleet-cron.js +35 -3
- package/dist/lib/bot/fleet-daemon.d.ts +46 -0
- package/dist/lib/bot/fleet-daemon.js +99 -1
- package/dist/lib/bot/fleet-local.d.ts +33 -1
- package/dist/lib/bot/fleet-local.js +215 -31
- package/dist/lib/bot/fleet-python.d.ts +3 -0
- package/dist/lib/bot/fleet-python.js +34 -4
- package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
- package/dist/lib/bot/fleet-runtime-sources.js +30 -0
- package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
- package/dist/lib/bot/legacy-provider-login.js +19 -2
- package/dist/lib/bot/probe.js +7 -1
- package/dist/lib/bot/prompt.js +1 -1
- package/dist/lib/bot/readiness.d.ts +8 -0
- package/dist/lib/bot/readiness.js +17 -3
- package/dist/lib/bot/run.js +20 -1
- package/dist/lib/bot/runtime/codex.js +1 -1
- package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
- package/dist/lib/bot/runtime/grok-acp.js +6 -3
- package/dist/lib/bot/runtime/index.js +19 -9
- package/dist/lib/bot/runtime/messages-stream.js +2 -2
- package/dist/lib/bot/runtime/types.d.ts +15 -0
- package/dist/lib/bot/runtime/types.js +9 -0
- package/dist/lib/bot/runtime-auth.d.ts +30 -0
- package/dist/lib/bot/runtime-auth.js +94 -3
- package/dist/lib/bot/runtime-failure.d.ts +23 -0
- package/dist/lib/bot/runtime-failure.js +43 -1
- package/dist/lib/bot/status.d.ts +2 -0
- package/dist/lib/capacity/accounts.d.ts +8 -0
- package/dist/lib/capacity/accounts.js +19 -0
- package/dist/lib/capacity/available.d.ts +154 -0
- package/dist/lib/capacity/available.js +905 -0
- package/dist/lib/capacity/codex-availability.d.ts +14 -1
- package/dist/lib/capacity/codex-availability.js +26 -1
- package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
- package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
- package/dist/lib/capacity/collectors/codex.js +10 -7
- package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
- package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
- package/dist/lib/capacity/collectors/grok.d.ts +5 -0
- package/dist/lib/capacity/collectors/grok.js +56 -5
- package/dist/lib/capacity/ledger.d.ts +37 -1
- package/dist/lib/capacity/ledger.js +207 -30
- package/dist/lib/capacity/project.d.ts +26 -0
- package/dist/lib/capacity/project.js +137 -8
- package/dist/lib/capacity/refusal-rows.d.ts +31 -0
- package/dist/lib/capacity/refusal-rows.js +61 -0
- package/dist/lib/capacity/refusal.d.ts +53 -2
- package/dist/lib/capacity/refusal.js +284 -65
- package/dist/lib/capacity/route.js +46 -11
- package/dist/lib/capacity/widget.d.ts +12 -1
- package/dist/lib/capacity/widget.js +91 -3
- package/dist/lib/daemon/catalog.js +11 -1
- package/dist/lib/daemon/resolver.d.ts +2 -0
- package/dist/lib/daemon/resolver.js +3 -0
- package/dist/lib/daemon/run.d.ts +9 -0
- package/dist/lib/daemon/run.js +54 -1
- package/dist/lib/daemon/server.d.ts +2 -0
- package/dist/lib/daemon/server.js +10 -1
- package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
- package/dist/lib/daemon/tcc-eperm.js +310 -0
- package/dist/lib/db/sqlite-binding.d.ts +1 -0
- package/dist/lib/db/sqlite-binding.js +1 -1
- package/dist/lib/delivery/admission.d.ts +86 -0
- package/dist/lib/delivery/admission.js +148 -0
- package/dist/lib/delivery/artifacts.d.ts +105 -0
- package/dist/lib/delivery/artifacts.js +567 -0
- package/dist/lib/delivery/attempt-id.d.ts +13 -0
- package/dist/lib/delivery/attempt-id.js +16 -0
- package/dist/lib/delivery/backup.d.ts +78 -0
- package/dist/lib/delivery/backup.js +343 -0
- package/dist/lib/delivery/cache.d.ts +29 -0
- package/dist/lib/delivery/cache.js +33 -0
- package/dist/lib/delivery/contracts.d.ts +142 -0
- package/dist/lib/delivery/contracts.js +289 -0
- package/dist/lib/delivery/credentials.d.ts +54 -0
- package/dist/lib/delivery/credentials.js +119 -0
- package/dist/lib/delivery/disposable-target.d.ts +42 -0
- package/dist/lib/delivery/disposable-target.js +111 -0
- package/dist/lib/delivery/effects.d.ts +136 -0
- package/dist/lib/delivery/effects.js +541 -0
- package/dist/lib/delivery/enrollment.d.ts +146 -0
- package/dist/lib/delivery/enrollment.js +460 -0
- package/dist/lib/delivery/escalations.d.ts +51 -0
- package/dist/lib/delivery/escalations.js +60 -0
- package/dist/lib/delivery/identity.d.ts +25 -0
- package/dist/lib/delivery/identity.js +82 -0
- package/dist/lib/delivery/inbox.d.ts +116 -0
- package/dist/lib/delivery/inbox.js +260 -0
- package/dist/lib/delivery/lease.d.ts +80 -0
- package/dist/lib/delivery/lease.js +134 -0
- package/dist/lib/delivery/migrations.d.ts +255 -0
- package/dist/lib/delivery/migrations.js +823 -0
- package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
- package/dist/lib/delivery/mqtt-adapter.js +242 -0
- package/dist/lib/delivery/mqtt.d.ts +63 -0
- package/dist/lib/delivery/mqtt.js +119 -0
- package/dist/lib/delivery/outbox.d.ts +95 -0
- package/dist/lib/delivery/outbox.js +187 -0
- package/dist/lib/delivery/provenance.d.ts +129 -0
- package/dist/lib/delivery/provenance.js +93 -0
- package/dist/lib/delivery/reconciler.d.ts +215 -0
- package/dist/lib/delivery/reconciler.js +703 -0
- package/dist/lib/delivery/restore.d.ts +35 -0
- package/dist/lib/delivery/restore.js +134 -0
- package/dist/lib/delivery/rpc/client.d.ts +22 -0
- package/dist/lib/delivery/rpc/client.js +159 -0
- package/dist/lib/delivery/rpc/port.d.ts +40 -0
- package/dist/lib/delivery/rpc/port.js +16 -0
- package/dist/lib/delivery/rpc/server.d.ts +30 -0
- package/dist/lib/delivery/rpc/server.js +205 -0
- package/dist/lib/delivery/rpc/wire.d.ts +85 -0
- package/dist/lib/delivery/rpc/wire.js +143 -0
- package/dist/lib/delivery/store.d.ts +163 -0
- package/dist/lib/delivery/store.js +944 -0
- package/dist/lib/delivery/windows-service-install.d.ts +262 -0
- package/dist/lib/delivery/windows-service-install.js +892 -0
- package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
- package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
- package/dist/lib/delivery/workers/macos.d.ts +191 -0
- package/dist/lib/delivery/workers/macos.js +943 -0
- package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
- package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
- package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
- package/dist/lib/delivery/workers/windows-service-live.js +711 -0
- package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
- package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
- package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
- package/dist/lib/delivery/workers/windows-service.js +584 -0
- package/dist/lib/delivery/workers/windows.d.ts +251 -0
- package/dist/lib/delivery/workers/windows.js +594 -0
- package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
- package/dist/lib/hot-channels/adapters/meetings.js +36 -3
- package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
- package/dist/lib/hot-channels/signals-pass.js +71 -2
- package/dist/lib/hot-channels/signals-redo.js +10 -2
- package/dist/lib/install/provider-wrappers.d.ts +2 -0
- package/dist/lib/install/provider-wrappers.js +68 -3
- package/dist/lib/lanes/watcher.js +35 -0
- package/dist/lib/signals/steps/extract.js +40 -4
- package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
- package/dist/utils/catalog-runtime-paths.d.ts +34 -0
- package/dist/utils/catalog-runtime-paths.js +53 -0
- package/dist/utils/cognito-callback-port.d.ts +14 -0
- package/dist/utils/cognito-callback-port.js +24 -0
- package/dist/utils/cognito-session.js +3 -3
- package/dist/utils/deleted-company-notice.d.ts +59 -0
- package/dist/utils/deleted-company-notice.js +156 -0
- package/dist/utils/files-browse-acl.js +1 -1
- package/dist/utils/login-browser.d.ts +1 -1
- package/dist/utils/login-browser.js +7 -5
- package/dist/utils/resident-package-preload.js +30 -15
- package/dist/utils/vault-api.js +7 -0
- package/package.json +7 -7
|
@@ -0,0 +1,823 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delivery store file format and schema migrations (US-003).
|
|
3
|
+
*
|
|
4
|
+
* The store file carries one store schema version, separate from the
|
|
5
|
+
* per-record versions in contracts.ts. A known older version migrates forward
|
|
6
|
+
* deterministically in memory; the store keeps a backup of the original bytes
|
|
7
|
+
* before the migrated state is written. An unknown, newer or damaged file
|
|
8
|
+
* never opens: parseStoreText throws a DeliveryStoreError that says what was
|
|
9
|
+
* found, what was expected and what the operator should do. Nothing here
|
|
10
|
+
* rewrites, repairs or drops data.
|
|
11
|
+
*
|
|
12
|
+
* validateState checks a whole state on load and before every write: every
|
|
13
|
+
* record passes the US-001 validators, ids are unique, references resolve,
|
|
14
|
+
* and the job dependency graph has no cycles.
|
|
15
|
+
*/
|
|
16
|
+
import { createHash } from "node:crypto";
|
|
17
|
+
import { validateRecord } from "./contracts.js";
|
|
18
|
+
import { PROVENANCE_SCHEMA_VERSION, TRUST_PARTITIONS, cacheKey as computeCacheKey, canonicalJson, sha256Hex } from "./provenance.js";
|
|
19
|
+
export const STORE_SCHEMA_V1 = "hq-delivery.store.v1";
|
|
20
|
+
export const STORE_SCHEMA_V2 = "hq-delivery.store.v2";
|
|
21
|
+
/** v3 (US-004) adds the worker list. */
|
|
22
|
+
export const STORE_SCHEMA_V3 = "hq-delivery.store.v3";
|
|
23
|
+
/** v4 binds each attempt to the worker that claimed it (claimedBy). */
|
|
24
|
+
export const STORE_SCHEMA_V4 = "hq-delivery.store.v4";
|
|
25
|
+
/** v5 (US-008) adds artifact provenance records and cache entries. */
|
|
26
|
+
export const STORE_SCHEMA_V5 = "hq-delivery.store.v5";
|
|
27
|
+
/** v6 (US-009) adds the deployment ledger: policy decisions and fenced deployments. */
|
|
28
|
+
export const STORE_SCHEMA_V6 = "hq-delivery.store.v6";
|
|
29
|
+
/** v7 (US-011 slice 4) adds a claim lease to every attempt (leaseExpiresAt). */
|
|
30
|
+
export const STORE_SCHEMA_V7 = "hq-delivery.store.v7";
|
|
31
|
+
/** The store schema version this code writes. */
|
|
32
|
+
export const STORE_SCHEMA_VERSION = STORE_SCHEMA_V7;
|
|
33
|
+
/** Every version this code can open, oldest first. Older ones migrate forward on open. */
|
|
34
|
+
export const KNOWN_STORE_SCHEMA_VERSIONS = [STORE_SCHEMA_V1, STORE_SCHEMA_V2, STORE_SCHEMA_V3, STORE_SCHEMA_V4, STORE_SCHEMA_V5, STORE_SCHEMA_V6, STORE_SCHEMA_V7];
|
|
35
|
+
const VERSION_PATTERN = /^hq-delivery\.store\.v(\d+)$/;
|
|
36
|
+
const CURRENT_VERSION_NUMBER = 7;
|
|
37
|
+
/** Every refusal from the delivery store. The message reads "CODE: found ...; expected .... action". */
|
|
38
|
+
export class DeliveryStoreError extends Error {
|
|
39
|
+
code;
|
|
40
|
+
found;
|
|
41
|
+
expected;
|
|
42
|
+
action;
|
|
43
|
+
constructor(code, detail) {
|
|
44
|
+
super(`${code}: found ${detail.found}; expected ${detail.expected}. ${detail.action}`);
|
|
45
|
+
this.name = "DeliveryStoreError";
|
|
46
|
+
this.code = code;
|
|
47
|
+
this.found = detail.found;
|
|
48
|
+
this.expected = detail.expected;
|
|
49
|
+
this.action = detail.action;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
export const WORKER_CAPABILITIES = ["claim", "read", "report"];
|
|
53
|
+
export const WORKER_TRUSTS = ["standard", "release"];
|
|
54
|
+
export const DEPLOYMENT_STATUSES = ["blocked", "in-flight", "unknown", "applied", "not-applied", "rejected"];
|
|
55
|
+
export const DECISION_CODES = [
|
|
56
|
+
"POLICY_INVALID",
|
|
57
|
+
"POLICY_MISSING",
|
|
58
|
+
"POLICY_TAMPERED",
|
|
59
|
+
"ENVIRONMENT_UNLISTED",
|
|
60
|
+
"ENVIRONMENT_UNAPPROVED",
|
|
61
|
+
"TARGET_MISMATCH",
|
|
62
|
+
"ATTEMPT_NOT_CURRENT",
|
|
63
|
+
"ARTIFACT_UNKNOWN",
|
|
64
|
+
"ARTIFACT_OTHER_TENANT",
|
|
65
|
+
"ARTIFACT_UNTRUSTED",
|
|
66
|
+
"ARTIFACT_CHANGED",
|
|
67
|
+
"ARTIFACT_UNPROMOTED",
|
|
68
|
+
"SOURCE_NOT_ALLOWED",
|
|
69
|
+
];
|
|
70
|
+
export const OBSERVATION_SOURCES = ["apply-response", "apply-rejected", "transport-error", "stale-publication", "lease-lost", "target-query"];
|
|
71
|
+
export function emptyState() {
|
|
72
|
+
return { epoch: 0, controllers: [], runs: [], jobs: [], attempts: [], workers: [], artifacts: [], cache: [], deployments: [], deployPolicies: [] };
|
|
73
|
+
}
|
|
74
|
+
export function stateChecksum(state) {
|
|
75
|
+
return createHash("sha256").update(JSON.stringify(state)).digest("hex");
|
|
76
|
+
}
|
|
77
|
+
/** The exact bytes of a current-version store file for `state`. */
|
|
78
|
+
export function serializeState(state) {
|
|
79
|
+
return `${JSON.stringify({ storeSchemaVersion: STORE_SCHEMA_VERSION, sha256: stateChecksum(state), state })}\n`;
|
|
80
|
+
}
|
|
81
|
+
const RESTORE_ACTION = "The store was not changed. Restore state.json from a backup, or move the store directory aside to start an empty store.";
|
|
82
|
+
function isObject(v) {
|
|
83
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Parse and validate a store file. A known older version is migrated forward
|
|
87
|
+
* in memory. Throws DeliveryStoreError for anything that cannot be opened
|
|
88
|
+
* exactly as written.
|
|
89
|
+
*/
|
|
90
|
+
export function parseStoreText(text, source) {
|
|
91
|
+
let parsed;
|
|
92
|
+
try {
|
|
93
|
+
parsed = JSON.parse(text);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
throw new DeliveryStoreError("STORE_CORRUPT", {
|
|
97
|
+
found: `${source} is not valid JSON (${text.length} bytes; truncated or damaged)`,
|
|
98
|
+
expected: `a complete ${STORE_SCHEMA_VERSION} store file`,
|
|
99
|
+
action: RESTORE_ACTION,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (!isObject(parsed) || typeof parsed.storeSchemaVersion !== "string") {
|
|
103
|
+
throw new DeliveryStoreError("STORE_CORRUPT", {
|
|
104
|
+
found: `${source} has no storeSchemaVersion field`,
|
|
105
|
+
expected: `a store file declaring one of ${KNOWN_STORE_SCHEMA_VERSIONS.join(", ")}`,
|
|
106
|
+
action: RESTORE_ACTION,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
const version = parsed.storeSchemaVersion;
|
|
110
|
+
const match = VERSION_PATTERN.exec(version);
|
|
111
|
+
if (match && Number(match[1]) > CURRENT_VERSION_NUMBER) {
|
|
112
|
+
throw new DeliveryStoreError("STORE_SCHEMA_NEWER", {
|
|
113
|
+
found: `${source} has store schema ${version}, newer than this HQ supports`,
|
|
114
|
+
expected: `one of ${KNOWN_STORE_SCHEMA_VERSIONS.join(", ")}`,
|
|
115
|
+
action: "Upgrade HQ to a version that supports this store before opening it. The store was not changed; do not edit or delete it.",
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
if (!KNOWN_STORE_SCHEMA_VERSIONS.includes(version)) {
|
|
119
|
+
throw new DeliveryStoreError("STORE_SCHEMA_UNKNOWN", {
|
|
120
|
+
found: `${source} has unknown store schema ${JSON.stringify(version)}`,
|
|
121
|
+
expected: `one of ${KNOWN_STORE_SCHEMA_VERSIONS.join(", ")}`,
|
|
122
|
+
action: "Check that this directory is a delivery store. The store was not changed; restore it from a backup or move it aside.",
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
const envelope = () => readEnvelope(parsed, source);
|
|
126
|
+
const state = version === STORE_SCHEMA_V7
|
|
127
|
+
? readEnvelope(parsed, source)
|
|
128
|
+
: version === STORE_SCHEMA_V6
|
|
129
|
+
? migrateV6(envelope(), source)
|
|
130
|
+
: version === STORE_SCHEMA_V5
|
|
131
|
+
? migrateV6(migrateV5(envelope(), source), source)
|
|
132
|
+
: version === STORE_SCHEMA_V4
|
|
133
|
+
? migrateV6(migrateV5(migrateV4(envelope(), source), source), source)
|
|
134
|
+
: version === STORE_SCHEMA_V3
|
|
135
|
+
? migrateV6(migrateV5(migrateV4(migrateV3(envelope(), source), source), source), source)
|
|
136
|
+
: version === STORE_SCHEMA_V2
|
|
137
|
+
? migrateV6(migrateV5(migrateV4(migrateV3(migrateV2(envelope(), source), source), source), source), source)
|
|
138
|
+
: migrateV6(migrateV5(migrateV4(migrateV1(parsed, source), source), source), source);
|
|
139
|
+
const errors = validateState(state);
|
|
140
|
+
if (errors.length > 0)
|
|
141
|
+
throw invalidStore(source, errors);
|
|
142
|
+
return { state, fromVersion: version === STORE_SCHEMA_VERSION ? null : version };
|
|
143
|
+
}
|
|
144
|
+
function invalidStore(source, errors) {
|
|
145
|
+
const shown = errors.slice(0, 5).join("; ");
|
|
146
|
+
const more = errors.length > 5 ? ` (+${errors.length - 5} more)` : "";
|
|
147
|
+
return new DeliveryStoreError("STORE_INVALID_RECORD", {
|
|
148
|
+
found: `${source}: ${shown}${more}`,
|
|
149
|
+
expected: "every record valid under the US-001 contracts, with unique ids and resolvable references",
|
|
150
|
+
action: "The store was not changed; HQ does not drop or repair records. Restore it from a backup.",
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* v4 → v5. v5 adds the artifact and cache lists, which start empty. The v4
|
|
155
|
+
* checksum is checked first, by readEnvelope.
|
|
156
|
+
*/
|
|
157
|
+
function migrateV4(state, source) {
|
|
158
|
+
if ("artifacts" in state || "cache" in state)
|
|
159
|
+
throw invalidStore(source, ["v4 state has an artifacts or cache field; v4 has none"]);
|
|
160
|
+
if ("deployments" in state || "deployPolicies" in state)
|
|
161
|
+
throw invalidStore(source, ["v4 state has a deployments or deployPolicies field; v4 has none"]);
|
|
162
|
+
return { ...state, artifacts: [], cache: [] };
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* v5 → v6. v6 adds the deployment ledger, which starts empty. The v5
|
|
166
|
+
* checksum is checked first, by readEnvelope.
|
|
167
|
+
*/
|
|
168
|
+
function migrateV5(state, source) {
|
|
169
|
+
if ("deployments" in state || "deployPolicies" in state)
|
|
170
|
+
throw invalidStore(source, ["v5 state has a deployments or deployPolicies field; v5 has none"]);
|
|
171
|
+
return { ...state, deployments: [], deployPolicies: [] };
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* v6 → v7. v7 adds leaseExpiresAt to every attempt. v6 had no claim lease, so
|
|
175
|
+
* every migrated attempt gets null: it never expires and behaves exactly as it
|
|
176
|
+
* did. An open v6 attempt is from an older epoch and is abandoned by the
|
|
177
|
+
* recovery rule when a controller opens, as before. The v6 checksum is checked
|
|
178
|
+
* first, by readEnvelope.
|
|
179
|
+
*/
|
|
180
|
+
function migrateV6(state, source) {
|
|
181
|
+
if (!Array.isArray(state.attempts))
|
|
182
|
+
return state;
|
|
183
|
+
const attempts = state.attempts.map((a) => {
|
|
184
|
+
if (typeof a === "object" && a !== null && "leaseExpiresAt" in a)
|
|
185
|
+
throw invalidStore(source, ["v6 attempt has a leaseExpiresAt field; v6 has none"]);
|
|
186
|
+
return { ...a, leaseExpiresAt: null };
|
|
187
|
+
});
|
|
188
|
+
return { ...state, attempts };
|
|
189
|
+
}
|
|
190
|
+
/** The v2 to v7 file envelope: exactly storeSchemaVersion, sha256 and state, with a matching checksum. */
|
|
191
|
+
function readEnvelope(parsed, source) {
|
|
192
|
+
const keys = Object.keys(parsed).sort().join(",");
|
|
193
|
+
if (keys !== "sha256,state,storeSchemaVersion" || typeof parsed.sha256 !== "string" || !isObject(parsed.state)) {
|
|
194
|
+
throw new DeliveryStoreError("STORE_CORRUPT", {
|
|
195
|
+
found: `${source} has fields [${keys}]`,
|
|
196
|
+
expected: "exactly storeSchemaVersion, sha256 and state",
|
|
197
|
+
action: RESTORE_ACTION,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
const actual = createHash("sha256").update(JSON.stringify(parsed.state)).digest("hex");
|
|
201
|
+
if (actual !== parsed.sha256) {
|
|
202
|
+
throw new DeliveryStoreError("STORE_CORRUPT", {
|
|
203
|
+
found: `${source} state checksum ${actual.slice(0, 12)}… does not match the recorded ${parsed.sha256.slice(0, 12)}…`,
|
|
204
|
+
expected: "the checksum written with the state",
|
|
205
|
+
action: RESTORE_ACTION,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
return parsed.state;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* v3 → v4. v4 adds claimedBy to every attempt. v3 did not record the
|
|
212
|
+
* claimant, so it is null: such an attempt can be reported or returned only
|
|
213
|
+
* through the controller, not by a worker. Open v3 attempts are from an older
|
|
214
|
+
* epoch and are abandoned by the recovery rule when a controller opens.
|
|
215
|
+
*/
|
|
216
|
+
function migrateV3(state, source) {
|
|
217
|
+
if (!Array.isArray(state.attempts))
|
|
218
|
+
return state;
|
|
219
|
+
const attempts = state.attempts.map((a) => {
|
|
220
|
+
if (typeof a === "object" && a !== null && "claimedBy" in a)
|
|
221
|
+
throw invalidStore(source, ["v3 attempt has a claimedBy field; v3 has none"]);
|
|
222
|
+
return { ...a, claimedBy: null };
|
|
223
|
+
});
|
|
224
|
+
return { ...state, attempts };
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* v2 → v3. v3 adds the worker list, which starts empty. The v2 checksum is
|
|
228
|
+
* checked first, by readEnvelope.
|
|
229
|
+
*/
|
|
230
|
+
function migrateV2(state, source) {
|
|
231
|
+
if ("workers" in state)
|
|
232
|
+
throw invalidStore(source, ["v2 state has a workers field; v2 has none"]);
|
|
233
|
+
return { ...state, workers: [] };
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* v1 → v4 (then v5 by migrateV4). v1 held { storeSchemaVersion, runs: Run[], jobs: { record, dependsOn }[],
|
|
237
|
+
* attempts: Attempt[] }. v2 adds the fencing epoch (starts at 0), the
|
|
238
|
+
* controller log, and accept, claim and resolution metadata. v1 did not record
|
|
239
|
+
* times, so they stay null. A pending v1 attempt becomes "open" and is
|
|
240
|
+
* resolved by the normal recovery rule when a controller opens the store.
|
|
241
|
+
*/
|
|
242
|
+
function migrateV1(parsed, source) {
|
|
243
|
+
const keys = Object.keys(parsed).sort().join(",");
|
|
244
|
+
const { runs, jobs, attempts } = parsed;
|
|
245
|
+
if (keys !== "attempts,jobs,runs,storeSchemaVersion" || !Array.isArray(runs) || !Array.isArray(jobs) || !Array.isArray(attempts)) {
|
|
246
|
+
throw invalidStore(source, [`v1 file has fields [${keys}]; expected arrays runs, jobs and attempts`]);
|
|
247
|
+
}
|
|
248
|
+
const badJob = jobs.findIndex((j) => !isObject(j) || Object.keys(j).sort().join(",") !== "dependsOn,record");
|
|
249
|
+
if (badJob !== -1)
|
|
250
|
+
throw invalidStore(source, [`v1 jobs[${badJob}] is not { record, dependsOn }`]);
|
|
251
|
+
return {
|
|
252
|
+
epoch: 0,
|
|
253
|
+
controllers: [],
|
|
254
|
+
runs: runs.map((record) => ({ record: record, acceptedAt: null, acceptedEpoch: 0 })),
|
|
255
|
+
jobs: jobs.map((j) => ({
|
|
256
|
+
record: j.record,
|
|
257
|
+
dependsOn: j.dependsOn,
|
|
258
|
+
acceptedAt: null,
|
|
259
|
+
acceptedEpoch: 0,
|
|
260
|
+
})),
|
|
261
|
+
attempts: attempts.map((record) => {
|
|
262
|
+
const pending = isObject(record) && record.outcome === "pending";
|
|
263
|
+
return {
|
|
264
|
+
record: record,
|
|
265
|
+
claimedAt: null,
|
|
266
|
+
claimedEpoch: 0,
|
|
267
|
+
claimedBy: null,
|
|
268
|
+
resolution: pending ? "open" : "reported",
|
|
269
|
+
resolvedAt: null,
|
|
270
|
+
resolvedEpoch: pending ? null : 0,
|
|
271
|
+
};
|
|
272
|
+
}),
|
|
273
|
+
workers: [],
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Return one dependency cycle as a path (a -> b -> a, where a depends on b),
|
|
278
|
+
* or null. Edges to nodes not in the graph are ignored.
|
|
279
|
+
*/
|
|
280
|
+
export function findCycle(graph) {
|
|
281
|
+
const color = new Map();
|
|
282
|
+
const path = [];
|
|
283
|
+
const visit = (node) => {
|
|
284
|
+
color.set(node, "active");
|
|
285
|
+
path.push(node);
|
|
286
|
+
for (const next of graph.get(node) ?? []) {
|
|
287
|
+
if (!graph.has(next))
|
|
288
|
+
continue;
|
|
289
|
+
const seen = color.get(next);
|
|
290
|
+
if (seen === "active")
|
|
291
|
+
return [...path.slice(path.indexOf(next)), next];
|
|
292
|
+
if (seen === undefined) {
|
|
293
|
+
const found = visit(next);
|
|
294
|
+
if (found)
|
|
295
|
+
return found;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
path.pop();
|
|
299
|
+
color.set(node, "done");
|
|
300
|
+
return null;
|
|
301
|
+
};
|
|
302
|
+
for (const node of graph.keys()) {
|
|
303
|
+
if (color.has(node))
|
|
304
|
+
continue;
|
|
305
|
+
const found = visit(node);
|
|
306
|
+
if (found)
|
|
307
|
+
return found;
|
|
308
|
+
}
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
const SHA256_HEX = /^[0-9a-f]{64}$/;
|
|
312
|
+
const STORE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
|
|
313
|
+
const RESOLUTIONS = ["open", "reported", "abandoned"];
|
|
314
|
+
const TAKEOVER_REASONS = ["stale-pid", "operator-override"];
|
|
315
|
+
function isCount(v) {
|
|
316
|
+
return typeof v === "number" && Number.isInteger(v) && v >= 0;
|
|
317
|
+
}
|
|
318
|
+
function isTimeOrNull(v) {
|
|
319
|
+
return v === null || (typeof v === "string" && STORE_TIME.test(v));
|
|
320
|
+
}
|
|
321
|
+
function hasExactKeys(v, keys, where, errors) {
|
|
322
|
+
if (!isObject(v)) {
|
|
323
|
+
errors.push(`${where}: not an object`);
|
|
324
|
+
return false;
|
|
325
|
+
}
|
|
326
|
+
const actual = Object.keys(v).sort().join(",");
|
|
327
|
+
const wanted = [...keys].sort().join(",");
|
|
328
|
+
if (actual !== wanted) {
|
|
329
|
+
errors.push(`${where}: fields [${actual}], expected [${wanted}]`);
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
function arrayAt(obj, key, errors) {
|
|
335
|
+
const v = obj[key];
|
|
336
|
+
if (Array.isArray(v))
|
|
337
|
+
return v;
|
|
338
|
+
errors.push(`state.${key}: not an array`);
|
|
339
|
+
return [];
|
|
340
|
+
}
|
|
341
|
+
function checkRecord(kind, input, where, errors) {
|
|
342
|
+
const res = validateRecord(kind, input);
|
|
343
|
+
if (res.ok)
|
|
344
|
+
return res.value;
|
|
345
|
+
errors.push(...res.errors.map((e) => `${where}.record: ${e}`));
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
/** All problems with a store state, or [] when it is valid. Never throws. */
|
|
349
|
+
export function validateState(input) {
|
|
350
|
+
const errors = [];
|
|
351
|
+
if (!hasExactKeys(input, ["epoch", "controllers", "runs", "jobs", "attempts", "workers", "artifacts", "cache", "deployments", "deployPolicies"], "state", errors))
|
|
352
|
+
return errors;
|
|
353
|
+
const epoch = isCount(input.epoch) ? input.epoch : null;
|
|
354
|
+
if (epoch === null)
|
|
355
|
+
errors.push("state.epoch: not a non-negative integer");
|
|
356
|
+
const checkEpoch = (v, where) => {
|
|
357
|
+
if (!isCount(v))
|
|
358
|
+
errors.push(`${where}: not a non-negative integer`);
|
|
359
|
+
else if (epoch !== null && v > epoch)
|
|
360
|
+
errors.push(`${where}: ${v} is after the store epoch ${epoch}`);
|
|
361
|
+
};
|
|
362
|
+
arrayAt(input, "controllers", errors).forEach((c, i) => {
|
|
363
|
+
const where = `controllers[${i}]`;
|
|
364
|
+
if (!hasExactKeys(c, ["epoch", "controllerId", "host", "pid", "acquiredAt", "takeover"], where, errors))
|
|
365
|
+
return;
|
|
366
|
+
checkEpoch(c.epoch, `${where}.epoch`);
|
|
367
|
+
if (typeof c.controllerId !== "string" || c.controllerId === "")
|
|
368
|
+
errors.push(`${where}.controllerId: not a non-empty string`);
|
|
369
|
+
if (typeof c.host !== "string")
|
|
370
|
+
errors.push(`${where}.host: not a string`);
|
|
371
|
+
if (!isCount(c.pid))
|
|
372
|
+
errors.push(`${where}.pid: not a non-negative integer`);
|
|
373
|
+
if (!isTimeOrNull(c.acquiredAt) || c.acquiredAt === null)
|
|
374
|
+
errors.push(`${where}.acquiredAt: not a timestamp`);
|
|
375
|
+
const t = c.takeover;
|
|
376
|
+
if (t !== null && hasExactKeys(t, ["reason", "previousOwner", "note"], `${where}.takeover`, errors)) {
|
|
377
|
+
if (!TAKEOVER_REASONS.includes(t.reason))
|
|
378
|
+
errors.push(`${where}.takeover.reason: unknown`);
|
|
379
|
+
if (typeof t.previousOwner !== "string")
|
|
380
|
+
errors.push(`${where}.takeover.previousOwner: not a string`);
|
|
381
|
+
if (t.note !== null && typeof t.note !== "string")
|
|
382
|
+
errors.push(`${where}.takeover.note: not a string or null`);
|
|
383
|
+
}
|
|
384
|
+
});
|
|
385
|
+
const runs = new Map();
|
|
386
|
+
arrayAt(input, "runs", errors).forEach((entry, i) => {
|
|
387
|
+
const where = `runs[${i}]`;
|
|
388
|
+
if (!hasExactKeys(entry, ["record", "acceptedAt", "acceptedEpoch"], where, errors))
|
|
389
|
+
return;
|
|
390
|
+
if (!isTimeOrNull(entry.acceptedAt))
|
|
391
|
+
errors.push(`${where}.acceptedAt: not a timestamp or null`);
|
|
392
|
+
checkEpoch(entry.acceptedEpoch, `${where}.acceptedEpoch`);
|
|
393
|
+
const run = checkRecord("run", entry.record, where, errors);
|
|
394
|
+
if (!run)
|
|
395
|
+
return;
|
|
396
|
+
if (runs.has(run.runId))
|
|
397
|
+
errors.push(`${where}: duplicate runId ${run.runId}`);
|
|
398
|
+
else
|
|
399
|
+
runs.set(run.runId, run);
|
|
400
|
+
});
|
|
401
|
+
const jobs = new Map();
|
|
402
|
+
arrayAt(input, "jobs", errors).forEach((entry, i) => {
|
|
403
|
+
const where = `jobs[${i}]`;
|
|
404
|
+
if (!hasExactKeys(entry, ["record", "dependsOn", "acceptedAt", "acceptedEpoch"], where, errors))
|
|
405
|
+
return;
|
|
406
|
+
if (!isTimeOrNull(entry.acceptedAt))
|
|
407
|
+
errors.push(`${where}.acceptedAt: not a timestamp or null`);
|
|
408
|
+
checkEpoch(entry.acceptedEpoch, `${where}.acceptedEpoch`);
|
|
409
|
+
const job = checkRecord("job", entry.record, where, errors);
|
|
410
|
+
const deps = entry.dependsOn;
|
|
411
|
+
if (!Array.isArray(deps) || !deps.every((d) => typeof d === "string" && d !== "")) {
|
|
412
|
+
errors.push(`${where}.dependsOn: not an array of jobIds`);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
if (new Set(deps).size !== deps.length)
|
|
416
|
+
errors.push(`${where}.dependsOn: duplicate jobId`);
|
|
417
|
+
if (!job)
|
|
418
|
+
return;
|
|
419
|
+
const run = runs.get(job.runId);
|
|
420
|
+
if (!run)
|
|
421
|
+
errors.push(`${where}: run ${job.runId} is not in the store`);
|
|
422
|
+
else if (run.tenantId !== job.tenantId)
|
|
423
|
+
errors.push(`${where}: tenant ${job.tenantId} does not match run tenant ${run.tenantId}`);
|
|
424
|
+
if (jobs.has(job.jobId))
|
|
425
|
+
errors.push(`${where}: duplicate jobId ${job.jobId}`);
|
|
426
|
+
else
|
|
427
|
+
jobs.set(job.jobId, { job, dependsOn: deps });
|
|
428
|
+
});
|
|
429
|
+
for (const [jobId, { job, dependsOn }] of jobs) {
|
|
430
|
+
for (const dep of dependsOn) {
|
|
431
|
+
const target = jobs.get(dep);
|
|
432
|
+
if (!target)
|
|
433
|
+
errors.push(`job ${jobId}: depends on unknown job ${dep}`);
|
|
434
|
+
else if (target.job.runId !== job.runId)
|
|
435
|
+
errors.push(`job ${jobId}: depends on ${dep} in another run`);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
const cycle = findCycle(new Map([...jobs].map(([id, j]) => [id, j.dependsOn])));
|
|
439
|
+
if (cycle)
|
|
440
|
+
errors.push(`dependency cycle ${cycle.join(" -> ")}`);
|
|
441
|
+
const attemptIds = new Set();
|
|
442
|
+
const attemptsById = new Map();
|
|
443
|
+
const perJob = new Map();
|
|
444
|
+
arrayAt(input, "attempts", errors).forEach((entry, i) => {
|
|
445
|
+
const where = `attempts[${i}]`;
|
|
446
|
+
if (!hasExactKeys(entry, ["record", "claimedAt", "claimedEpoch", "claimedBy", "leaseExpiresAt", "resolution", "resolvedAt", "resolvedEpoch"], where, errors))
|
|
447
|
+
return;
|
|
448
|
+
if (entry.claimedBy !== null && (typeof entry.claimedBy !== "string" || entry.claimedBy === ""))
|
|
449
|
+
errors.push(`${where}.claimedBy: not a workerId or null`);
|
|
450
|
+
if (!isTimeOrNull(entry.leaseExpiresAt))
|
|
451
|
+
errors.push(`${where}.leaseExpiresAt: not a timestamp or null`);
|
|
452
|
+
else if (entry.leaseExpiresAt !== null && entry.claimedBy === null)
|
|
453
|
+
errors.push(`${where}.leaseExpiresAt: a lease needs the worker that claimed the attempt`);
|
|
454
|
+
if (!isTimeOrNull(entry.claimedAt))
|
|
455
|
+
errors.push(`${where}.claimedAt: not a timestamp or null`);
|
|
456
|
+
if (!isTimeOrNull(entry.resolvedAt))
|
|
457
|
+
errors.push(`${where}.resolvedAt: not a timestamp or null`);
|
|
458
|
+
checkEpoch(entry.claimedEpoch, `${where}.claimedEpoch`);
|
|
459
|
+
if (entry.resolvedEpoch !== null)
|
|
460
|
+
checkEpoch(entry.resolvedEpoch, `${where}.resolvedEpoch`);
|
|
461
|
+
const resolution = entry.resolution;
|
|
462
|
+
if (!RESOLUTIONS.includes(resolution))
|
|
463
|
+
errors.push(`${where}.resolution: unknown ${JSON.stringify(entry.resolution)}`);
|
|
464
|
+
const attempt = checkRecord("attempt", entry.record, where, errors);
|
|
465
|
+
if (!attempt)
|
|
466
|
+
return;
|
|
467
|
+
if (attemptIds.has(attempt.attemptId))
|
|
468
|
+
errors.push(`${where}: duplicate attemptId ${attempt.attemptId}`);
|
|
469
|
+
attemptIds.add(attempt.attemptId);
|
|
470
|
+
attemptsById.set(attempt.attemptId, attempt);
|
|
471
|
+
const owner = jobs.get(attempt.jobId);
|
|
472
|
+
if (!owner)
|
|
473
|
+
errors.push(`${where}: job ${attempt.jobId} is not in the store`);
|
|
474
|
+
else if (owner.job.runId !== attempt.runId || owner.job.tenantId !== attempt.tenantId) {
|
|
475
|
+
errors.push(`${where}: tenant or run does not match job ${attempt.jobId}`);
|
|
476
|
+
}
|
|
477
|
+
if (resolution === "open" && (attempt.outcome !== "pending" || entry.resolvedEpoch !== null)) {
|
|
478
|
+
errors.push(`${where}: an open attempt must be pending and unresolved`);
|
|
479
|
+
}
|
|
480
|
+
if (resolution === "reported" && (attempt.outcome === "pending" || entry.resolvedEpoch === null)) {
|
|
481
|
+
errors.push(`${where}: a reported attempt must have a final outcome and a resolvedEpoch`);
|
|
482
|
+
}
|
|
483
|
+
if (resolution === "abandoned" && (attempt.outcome !== "failed" || entry.resolvedEpoch === null)) {
|
|
484
|
+
errors.push(`${where}: an abandoned attempt must be failed and have a resolvedEpoch`);
|
|
485
|
+
}
|
|
486
|
+
const tally = perJob.get(attempt.jobId) ?? { numbers: new Set(), open: 0, passed: 0 };
|
|
487
|
+
if (tally.numbers.has(attempt.number))
|
|
488
|
+
errors.push(`${where}: duplicate attempt number ${attempt.number} for job ${attempt.jobId}`);
|
|
489
|
+
tally.numbers.add(attempt.number);
|
|
490
|
+
if (resolution === "open")
|
|
491
|
+
tally.open += 1;
|
|
492
|
+
if (attempt.outcome === "passed")
|
|
493
|
+
tally.passed += 1;
|
|
494
|
+
perJob.set(attempt.jobId, tally);
|
|
495
|
+
});
|
|
496
|
+
for (const [jobId, tally] of perJob) {
|
|
497
|
+
if (tally.open > 1)
|
|
498
|
+
errors.push(`job ${jobId}: ${tally.open} open attempts, at most 1 allowed`);
|
|
499
|
+
if (tally.passed > 1)
|
|
500
|
+
errors.push(`job ${jobId}: ${tally.passed} passed attempts, at most 1 allowed`);
|
|
501
|
+
}
|
|
502
|
+
const workerIds = new Set();
|
|
503
|
+
const secrets = new Set();
|
|
504
|
+
arrayAt(input, "workers", errors).forEach((w, i) => {
|
|
505
|
+
const where = `workers[${i}]`;
|
|
506
|
+
const fields = ["workerId", "tenantId", "capabilities", "trust", "status", "secretSha256", "issuedAt", "issuedEpoch"];
|
|
507
|
+
if (!hasExactKeys(w, [...fields, "enrolledAt", "enrolledEpoch", "revokedAt", "revokedEpoch"], where, errors))
|
|
508
|
+
return;
|
|
509
|
+
if (typeof w.workerId !== "string" || w.workerId === "")
|
|
510
|
+
errors.push(`${where}.workerId: not a non-empty string`);
|
|
511
|
+
else if (workerIds.has(w.workerId))
|
|
512
|
+
errors.push(`${where}: duplicate workerId ${w.workerId}`);
|
|
513
|
+
else
|
|
514
|
+
workerIds.add(w.workerId);
|
|
515
|
+
if (typeof w.tenantId !== "string" || w.tenantId === "")
|
|
516
|
+
errors.push(`${where}.tenantId: not a non-empty string`);
|
|
517
|
+
if (typeof w.secretSha256 !== "string" || !SHA256_HEX.test(w.secretSha256))
|
|
518
|
+
errors.push(`${where}.secretSha256: not a SHA-256 hex digest`);
|
|
519
|
+
else if (secrets.has(w.secretSha256))
|
|
520
|
+
errors.push(`${where}: duplicate secret digest`);
|
|
521
|
+
else
|
|
522
|
+
secrets.add(w.secretSha256);
|
|
523
|
+
const caps = w.capabilities;
|
|
524
|
+
if (!Array.isArray(caps) || !caps.every((c) => WORKER_CAPABILITIES.includes(c))) {
|
|
525
|
+
errors.push(`${where}.capabilities: not a list of ${WORKER_CAPABILITIES.join(", ")}`);
|
|
526
|
+
}
|
|
527
|
+
else if (new Set(caps).size !== caps.length)
|
|
528
|
+
errors.push(`${where}.capabilities: duplicate capability`);
|
|
529
|
+
if (!WORKER_TRUSTS.includes(w.trust))
|
|
530
|
+
errors.push(`${where}.trust: unknown ${JSON.stringify(w.trust)}`);
|
|
531
|
+
if (!isTimeOrNull(w.issuedAt) || w.issuedAt === null)
|
|
532
|
+
errors.push(`${where}.issuedAt: not a timestamp`);
|
|
533
|
+
checkEpoch(w.issuedEpoch, `${where}.issuedEpoch`);
|
|
534
|
+
for (const key of ["enrolledAt", "revokedAt"]) {
|
|
535
|
+
if (!isTimeOrNull(w[key]))
|
|
536
|
+
errors.push(`${where}.${key}: not a timestamp or null`);
|
|
537
|
+
}
|
|
538
|
+
for (const key of ["enrolledEpoch", "revokedEpoch"]) {
|
|
539
|
+
if (w[key] !== null)
|
|
540
|
+
checkEpoch(w[key], `${where}.${key}`);
|
|
541
|
+
}
|
|
542
|
+
const enrolled = w.enrolledAt !== null || w.enrolledEpoch !== null;
|
|
543
|
+
const enrolledBoth = w.enrolledAt !== null && w.enrolledEpoch !== null;
|
|
544
|
+
const revoked = w.revokedAt !== null || w.revokedEpoch !== null;
|
|
545
|
+
const revokedBoth = w.revokedAt !== null && w.revokedEpoch !== null;
|
|
546
|
+
if (w.status === "pending" && (enrolled || revoked))
|
|
547
|
+
errors.push(`${where}: a pending worker must have no enrolled or revoked fields`);
|
|
548
|
+
else if (w.status === "active" && (!enrolledBoth || revoked))
|
|
549
|
+
errors.push(`${where}: an active worker must be enrolled and not revoked`);
|
|
550
|
+
else if (w.status === "revoked" && (!revokedBoth || enrolled !== enrolledBoth)) {
|
|
551
|
+
errors.push(`${where}: a revoked worker must have revokedAt and revokedEpoch, and complete enrolled fields if any`);
|
|
552
|
+
}
|
|
553
|
+
else if (!["pending", "active", "revoked"].includes(w.status))
|
|
554
|
+
errors.push(`${where}.status: unknown ${JSON.stringify(w.status)}`);
|
|
555
|
+
});
|
|
556
|
+
validateArtifacts(input, attemptsById, checkEpoch, errors);
|
|
557
|
+
validateDeployments(input, attemptsById, checkEpoch, errors);
|
|
558
|
+
validateDeployPolicies(input, checkEpoch, errors);
|
|
559
|
+
return errors;
|
|
560
|
+
}
|
|
561
|
+
const isHex64 = (v) => typeof v === "string" && SHA256_HEX.test(v);
|
|
562
|
+
const isText = (v) => typeof v === "string" && v !== "";
|
|
563
|
+
/** US-008 artifact provenance and cache entries. Signatures are checked by artifacts.ts, which holds the key. */
|
|
564
|
+
function validateArtifacts(input, attempts, checkEpoch, errors) {
|
|
565
|
+
const byId = new Map();
|
|
566
|
+
arrayAt(input, "artifacts", errors).forEach((a, i) => {
|
|
567
|
+
const where = `artifacts[${i}]`;
|
|
568
|
+
if (!hasExactKeys(a, ["record", "provenance", "signature", "promotedAt", "promotedEpoch", "promotionSignature"], where, errors))
|
|
569
|
+
return;
|
|
570
|
+
const record = checkRecord("artifact", a.record, where, errors);
|
|
571
|
+
const p = a.provenance;
|
|
572
|
+
const fields = ["schemaVersion", "artifactId", "tenantId", "name", "partition", "digest", "size", "source", "recipe", "toolchain"];
|
|
573
|
+
const more = ["platform", "envKeys", "envDigest", "inputDigest", "builder", "attempt", "createdAt", "createdEpoch"];
|
|
574
|
+
if (!hasExactKeys(p, [...fields, ...more], `${where}.provenance`, errors))
|
|
575
|
+
return;
|
|
576
|
+
const w = `${where}.provenance`;
|
|
577
|
+
if (p.schemaVersion !== PROVENANCE_SCHEMA_VERSION)
|
|
578
|
+
errors.push(`${w}.schemaVersion: unsupported ${JSON.stringify(p.schemaVersion)}`);
|
|
579
|
+
for (const key of ["artifactId", "tenantId", "name"])
|
|
580
|
+
if (!isText(p[key]))
|
|
581
|
+
errors.push(`${w}.${key}: not a non-empty string`);
|
|
582
|
+
if (!TRUST_PARTITIONS.includes(p.partition))
|
|
583
|
+
errors.push(`${w}.partition: unknown ${JSON.stringify(p.partition)}`);
|
|
584
|
+
const d = p.digest;
|
|
585
|
+
if (!hasExactKeys(d, ["algorithm", "value"], `${w}.digest`, errors) || d.algorithm !== "sha256" || !isHex64(d.value)) {
|
|
586
|
+
errors.push(`${w}.digest: not a sha256 digest`);
|
|
587
|
+
}
|
|
588
|
+
if (!isCount(p.size))
|
|
589
|
+
errors.push(`${w}.size: not a non-negative integer`);
|
|
590
|
+
const src = p.source;
|
|
591
|
+
if (!hasExactKeys(src, ["repository", "commitSha", "ref"], `${w}.source`, errors) || !isText(src.repository) || !isText(src.ref) || typeof src.commitSha !== "string" || !/^[0-9a-f]{40}$/.test(src.commitSha)) {
|
|
592
|
+
errors.push(`${w}.source: not a repository, 40-hex commitSha and ref`);
|
|
593
|
+
}
|
|
594
|
+
const rec = p.recipe;
|
|
595
|
+
if (!hasExactKeys(rec, ["recipeId", "digest"], `${w}.recipe`, errors) || !isText(rec.recipeId) || !isHex64(rec.digest))
|
|
596
|
+
errors.push(`${w}.recipe: not a recipeId and sha256 digest`);
|
|
597
|
+
if (!isObject(p.toolchain) || !Object.entries(p.toolchain).every(([k, v]) => k !== "" && isText(v)))
|
|
598
|
+
errors.push(`${w}.toolchain: not a map of name to version`);
|
|
599
|
+
const plat = p.platform;
|
|
600
|
+
if (!hasExactKeys(plat, ["os", "arch"], `${w}.platform`, errors) || !isText(plat.os) || !isText(plat.arch))
|
|
601
|
+
errors.push(`${w}.platform: not an os and arch`);
|
|
602
|
+
if (!Array.isArray(p.envKeys) || !p.envKeys.every(isText))
|
|
603
|
+
errors.push(`${w}.envKeys: not a list of keys`);
|
|
604
|
+
if (!isHex64(p.envDigest))
|
|
605
|
+
errors.push(`${w}.envDigest: not a sha256 digest`);
|
|
606
|
+
if (!isHex64(p.inputDigest))
|
|
607
|
+
errors.push(`${w}.inputDigest: not a sha256 digest`);
|
|
608
|
+
const b = p.builder;
|
|
609
|
+
if (!hasExactKeys(b, ["workerId", "trust"], `${w}.builder`, errors) || !isText(b.workerId) || !WORKER_TRUSTS.includes(b.trust)) {
|
|
610
|
+
errors.push(`${w}.builder: not a workerId and trust`);
|
|
611
|
+
}
|
|
612
|
+
else if ((b.trust === "release") !== (p.partition === "release"))
|
|
613
|
+
errors.push(`${w}: partition ${String(p.partition)} does not match builder trust ${String(b.trust)}`);
|
|
614
|
+
if (!isTimeOrNull(p.createdAt) || p.createdAt === null)
|
|
615
|
+
errors.push(`${w}.createdAt: not a timestamp`);
|
|
616
|
+
checkEpoch(p.createdEpoch, `${w}.createdEpoch`);
|
|
617
|
+
const at = p.attempt;
|
|
618
|
+
if (!hasExactKeys(at, ["attemptId", "jobId", "runId", "number"], `${w}.attempt`, errors))
|
|
619
|
+
return;
|
|
620
|
+
const stored = attempts.get(at.attemptId);
|
|
621
|
+
if (!stored)
|
|
622
|
+
errors.push(`${w}: attempt ${String(at.attemptId)} is not in the store`);
|
|
623
|
+
else if (stored.tenantId !== p.tenantId || stored.jobId !== at.jobId || stored.runId !== at.runId || stored.number !== at.number) {
|
|
624
|
+
errors.push(`${w}: tenant, job, run or number does not match attempt ${stored.attemptId}`);
|
|
625
|
+
}
|
|
626
|
+
if (record && (record.artifactId !== p.artifactId || record.tenantId !== p.tenantId || record.runId !== at.runId)) {
|
|
627
|
+
errors.push(`${where}.record: does not match its provenance`);
|
|
628
|
+
}
|
|
629
|
+
const sig = a.signature;
|
|
630
|
+
if (!hasExactKeys(sig, ["algorithm", "keyRef", "value"], `${where}.signature`, errors) || sig.algorithm !== "hmac-sha256" || !isText(sig.keyRef) || !isHex64(sig.value)) {
|
|
631
|
+
errors.push(`${where}.signature: not an hmac-sha256 signature`);
|
|
632
|
+
}
|
|
633
|
+
const ps = a.promotionSignature;
|
|
634
|
+
if (!hasExactKeys(ps, ["algorithm", "keyRef", "value"], `${where}.promotionSignature`, errors) || ps.algorithm !== "hmac-sha256" || !isText(ps.keyRef) || !isHex64(ps.value)) {
|
|
635
|
+
errors.push(`${where}.promotionSignature: not an hmac-sha256 signature`);
|
|
636
|
+
}
|
|
637
|
+
if ((a.promotedAt === null) !== (a.promotedEpoch === null) || !isTimeOrNull(a.promotedAt))
|
|
638
|
+
errors.push(`${where}: promotedAt and promotedEpoch must both be set or both null`);
|
|
639
|
+
if (a.promotedEpoch !== null)
|
|
640
|
+
checkEpoch(a.promotedEpoch, `${where}.promotedEpoch`);
|
|
641
|
+
if (a.promotedAt !== null && p.partition !== "release")
|
|
642
|
+
errors.push(`${where}: an untrusted artifact cannot be promoted`);
|
|
643
|
+
if (typeof p.artifactId === "string") {
|
|
644
|
+
if (byId.has(p.artifactId))
|
|
645
|
+
errors.push(`${where}: duplicate artifactId ${p.artifactId}`);
|
|
646
|
+
else
|
|
647
|
+
byId.set(p.artifactId, p);
|
|
648
|
+
}
|
|
649
|
+
});
|
|
650
|
+
const keys = new Set();
|
|
651
|
+
arrayAt(input, "cache", errors).forEach((c, i) => {
|
|
652
|
+
const where = `cache[${i}]`;
|
|
653
|
+
if (!hasExactKeys(c, ["cacheKey", "tenantId", "partition", "inputDigest", "slot", "artifactId", "createdAt", "createdEpoch"], where, errors))
|
|
654
|
+
return;
|
|
655
|
+
for (const key of ["cacheKey", "inputDigest", "slot"])
|
|
656
|
+
if (!isHex64(c[key]))
|
|
657
|
+
errors.push(`${where}.${key}: not a sha256 digest`);
|
|
658
|
+
if (!TRUST_PARTITIONS.includes(c.partition))
|
|
659
|
+
errors.push(`${where}.partition: unknown ${JSON.stringify(c.partition)}`);
|
|
660
|
+
if (!isTimeOrNull(c.createdAt) || c.createdAt === null)
|
|
661
|
+
errors.push(`${where}.createdAt: not a timestamp`);
|
|
662
|
+
checkEpoch(c.createdEpoch, `${where}.createdEpoch`);
|
|
663
|
+
if (typeof c.cacheKey === "string") {
|
|
664
|
+
if (keys.has(c.cacheKey))
|
|
665
|
+
errors.push(`${where}: duplicate cacheKey`);
|
|
666
|
+
keys.add(c.cacheKey);
|
|
667
|
+
}
|
|
668
|
+
const p = byId.get(c.artifactId);
|
|
669
|
+
if (!p)
|
|
670
|
+
errors.push(`${where}: artifact ${String(c.artifactId)} is not in the store`);
|
|
671
|
+
else if (p.tenantId !== c.tenantId || p.partition !== c.partition || p.inputDigest !== c.inputDigest) {
|
|
672
|
+
errors.push(`${where}: tenant, partition or inputs do not match artifact ${p.artifactId}`);
|
|
673
|
+
}
|
|
674
|
+
else {
|
|
675
|
+
// The key and slot must be the ones the artifact's signed provenance yields, so an entry cannot be repointed.
|
|
676
|
+
if (c.cacheKey !== computeCacheKey(p.tenantId, p.partition, p.inputDigest))
|
|
677
|
+
errors.push(`${where}.cacheKey: does not match the inputs of artifact ${p.artifactId}`);
|
|
678
|
+
if (c.slot !== sha256Hex(canonicalJson({ source: p.source, recipeId: p.recipe?.recipeId })))
|
|
679
|
+
errors.push(`${where}.slot: does not match the source and recipe of artifact ${p.artifactId}`);
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
const DEPLOYMENT_KEYS = [
|
|
684
|
+
"deploymentId",
|
|
685
|
+
"tenantId",
|
|
686
|
+
"environment",
|
|
687
|
+
"artifactId",
|
|
688
|
+
"digest",
|
|
689
|
+
"workerId",
|
|
690
|
+
"attemptId",
|
|
691
|
+
"targetId",
|
|
692
|
+
"fence",
|
|
693
|
+
"status",
|
|
694
|
+
"snapshot",
|
|
695
|
+
"snapshotDigest",
|
|
696
|
+
"snapshotSignature",
|
|
697
|
+
"decision",
|
|
698
|
+
"requestedAt",
|
|
699
|
+
"requestedEpoch",
|
|
700
|
+
"resolvedAt",
|
|
701
|
+
"resolvedEpoch",
|
|
702
|
+
"observation",
|
|
703
|
+
];
|
|
704
|
+
/**
|
|
705
|
+
* US-009 deployment ledger. Each snapshot must hash to its snapshotDigest, so
|
|
706
|
+
* an edited snapshot does not open even with the store checksum recomputed.
|
|
707
|
+
* Fences are unique per tenant/environment and at most one deployment per
|
|
708
|
+
* tenant/environment is in flight or unknown.
|
|
709
|
+
*/
|
|
710
|
+
function validateDeployments(input, attempts, checkEpoch, errors) {
|
|
711
|
+
const ids = new Set();
|
|
712
|
+
const fences = new Map();
|
|
713
|
+
const open = new Set();
|
|
714
|
+
arrayAt(input, "deployments", errors).forEach((d, i) => {
|
|
715
|
+
const where = `deployments[${i}]`;
|
|
716
|
+
if (!hasExactKeys(d, DEPLOYMENT_KEYS, where, errors))
|
|
717
|
+
return;
|
|
718
|
+
for (const key of ["deploymentId", "tenantId", "environment", "artifactId", "digest", "workerId", "attemptId"]) {
|
|
719
|
+
if (!isText(d[key]))
|
|
720
|
+
errors.push(`${where}.${key}: not a non-empty string`);
|
|
721
|
+
}
|
|
722
|
+
if (isText(d.deploymentId)) {
|
|
723
|
+
if (ids.has(d.deploymentId))
|
|
724
|
+
errors.push(`${where}: duplicate deploymentId ${d.deploymentId}`);
|
|
725
|
+
ids.add(d.deploymentId);
|
|
726
|
+
}
|
|
727
|
+
if (d.targetId !== null && !isText(d.targetId))
|
|
728
|
+
errors.push(`${where}.targetId: not a string or null`);
|
|
729
|
+
const status = d.status;
|
|
730
|
+
if (!DEPLOYMENT_STATUSES.includes(status))
|
|
731
|
+
errors.push(`${where}.status: unknown ${JSON.stringify(d.status)}`);
|
|
732
|
+
if (!isTimeOrNull(d.requestedAt) || d.requestedAt === null)
|
|
733
|
+
errors.push(`${where}.requestedAt: not a timestamp`);
|
|
734
|
+
checkEpoch(d.requestedEpoch, `${where}.requestedEpoch`);
|
|
735
|
+
if (!isTimeOrNull(d.resolvedAt))
|
|
736
|
+
errors.push(`${where}.resolvedAt: not a timestamp or null`);
|
|
737
|
+
if (d.resolvedEpoch !== null)
|
|
738
|
+
checkEpoch(d.resolvedEpoch, `${where}.resolvedEpoch`);
|
|
739
|
+
if (!isObject(d.snapshot))
|
|
740
|
+
errors.push(`${where}.snapshot: not an object`);
|
|
741
|
+
else {
|
|
742
|
+
if (d.snapshotDigest !== sha256Hex(canonicalJson(d.snapshot)))
|
|
743
|
+
errors.push(`${where}.snapshotDigest: does not match the snapshot`);
|
|
744
|
+
const sig = d.snapshotSignature;
|
|
745
|
+
if (!isObject(sig) || sig.algorithm !== "hmac-sha256" || !isText(sig.keyRef) || !isHex64(sig.value))
|
|
746
|
+
errors.push(`${where}.snapshotSignature: not an hmac-sha256 signature`);
|
|
747
|
+
const ctx = d.snapshot.context;
|
|
748
|
+
if (!isObject(ctx) || ctx.tenantId !== d.tenantId || ctx.environment !== d.environment || ctx.attemptId !== d.attemptId || ctx.workerId !== d.workerId) {
|
|
749
|
+
errors.push(`${where}.snapshot.context: does not name this deployment's tenant, environment, worker and attempt`);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
const key = `${String(d.tenantId)}\u0000${String(d.environment)}`;
|
|
753
|
+
if (status === "blocked") {
|
|
754
|
+
if (d.fence !== null)
|
|
755
|
+
errors.push(`${where}.fence: a blocked request has no fence`);
|
|
756
|
+
const dec = d.decision;
|
|
757
|
+
if (!hasExactKeys(dec, ["code", "found", "scope", "escalateTo", "resolution"], `${where}.decision`, errors))
|
|
758
|
+
return;
|
|
759
|
+
if (!DECISION_CODES.includes(dec.code))
|
|
760
|
+
errors.push(`${where}.decision.code: unknown ${JSON.stringify(dec.code)}`);
|
|
761
|
+
const scope = dec.scope;
|
|
762
|
+
if (!isObject(scope) || scope.tenantId !== d.tenantId || scope.environment !== d.environment)
|
|
763
|
+
errors.push(`${where}.decision.scope: not this deployment's tenant and environment`);
|
|
764
|
+
if (!isText(dec.escalateTo) || dec.resolution !== "pending" || typeof dec.found !== "string")
|
|
765
|
+
errors.push(`${where}.decision: malformed`);
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
if (d.decision !== null)
|
|
769
|
+
errors.push(`${where}.decision: only a blocked request has a decision`);
|
|
770
|
+
if (typeof d.fence !== "number" || !Number.isInteger(d.fence) || d.fence < 1)
|
|
771
|
+
errors.push(`${where}.fence: not a positive integer`);
|
|
772
|
+
else {
|
|
773
|
+
const seen = fences.get(key) ?? new Set();
|
|
774
|
+
if (seen.has(d.fence))
|
|
775
|
+
errors.push(`${where}.fence: duplicate fence ${d.fence} for this tenant and environment`);
|
|
776
|
+
seen.add(d.fence);
|
|
777
|
+
fences.set(key, seen);
|
|
778
|
+
}
|
|
779
|
+
const attempt = typeof d.attemptId === "string" ? attempts.get(d.attemptId) : undefined;
|
|
780
|
+
if (!attempt)
|
|
781
|
+
errors.push(`${where}.attemptId: no attempt ${String(d.attemptId)}`);
|
|
782
|
+
else if (attempt.tenantId !== d.tenantId)
|
|
783
|
+
errors.push(`${where}.attemptId: attempt of another tenant`);
|
|
784
|
+
if (status === "in-flight" || status === "unknown") {
|
|
785
|
+
if (open.has(key))
|
|
786
|
+
errors.push(`${where}: a second in-flight or unknown deployment for this tenant and environment`);
|
|
787
|
+
open.add(key);
|
|
788
|
+
}
|
|
789
|
+
if (d.observation !== null) {
|
|
790
|
+
const o = d.observation;
|
|
791
|
+
if (!hasExactKeys(o, ["source", "detail", "fence", "digest"], `${where}.observation`, errors))
|
|
792
|
+
return;
|
|
793
|
+
if (!OBSERVATION_SOURCES.includes(o.source))
|
|
794
|
+
errors.push(`${where}.observation.source: unknown ${JSON.stringify(o.source)}`);
|
|
795
|
+
}
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
function validateDeployPolicies(input, checkEpoch, errors) {
|
|
799
|
+
const tenants = new Set();
|
|
800
|
+
arrayAt(input, "deployPolicies", errors).forEach((p, i) => {
|
|
801
|
+
const where = `deployPolicies[${i}]`;
|
|
802
|
+
if (!hasExactKeys(p, ["tenantId", "policy", "setBy", "setAt", "setEpoch", "signature"], where, errors))
|
|
803
|
+
return;
|
|
804
|
+
if (!isText(p.tenantId))
|
|
805
|
+
errors.push(`${where}.tenantId: not a non-empty string`);
|
|
806
|
+
else if (tenants.has(p.tenantId))
|
|
807
|
+
errors.push(`${where}: a second policy for ${p.tenantId}`);
|
|
808
|
+
else
|
|
809
|
+
tenants.add(p.tenantId);
|
|
810
|
+
if (!isObject(p.policy) || p.policy.tenantId !== p.tenantId)
|
|
811
|
+
errors.push(`${where}.policy: not a policy of ${String(p.tenantId)}`);
|
|
812
|
+
if (!isText(p.setBy))
|
|
813
|
+
errors.push(`${where}.setBy: not a credential ref`);
|
|
814
|
+
if (!isTimeOrNull(p.setAt) || p.setAt === null)
|
|
815
|
+
errors.push(`${where}.setAt: not a timestamp`);
|
|
816
|
+
checkEpoch(p.setEpoch, `${where}.setEpoch`);
|
|
817
|
+
const s = p.signature;
|
|
818
|
+
if (!hasExactKeys(s, ["algorithm", "keyRef", "value"], `${where}.signature`, errors) || s.algorithm !== "hmac-sha256" || !isText(s.keyRef) || !isHex64(s.value)) {
|
|
819
|
+
errors.push(`${where}.signature: not an hmac-sha256 signature`);
|
|
820
|
+
}
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
//# sourceMappingURL=migrations.js.map
|