@akilium/telemetry-collector 0.1.9 → 0.1.11

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.
Files changed (35) hide show
  1. package/README.md +28 -1
  2. package/bin/akilium-telemetry.mjs +0 -0
  3. package/bin/status-reporter.mjs +1 -1
  4. package/dist/instrumentation/src/client.d.ts +77 -0
  5. package/dist/instrumentation/src/client.js +237 -0
  6. package/dist/instrumentation/src/codex-cli.d.ts +20 -0
  7. package/dist/instrumentation/src/codex-cli.js +92 -0
  8. package/dist/instrumentation/src/codex-execution.d.ts +27 -0
  9. package/dist/instrumentation/src/codex-execution.js +123 -0
  10. package/dist/instrumentation/src/index.d.ts +11 -0
  11. package/dist/instrumentation/src/index.js +11 -0
  12. package/dist/instrumentation/src/persisted-file.d.ts +18 -0
  13. package/dist/instrumentation/src/persisted-file.js +65 -0
  14. package/dist/instrumentation/src/posting-wrappers.d.ts +49 -0
  15. package/dist/instrumentation/src/posting-wrappers.js +76 -0
  16. package/dist/instrumentation/src/wrappers.d.ts +68 -0
  17. package/dist/instrumentation/src/wrappers.js +76 -0
  18. package/dist/integration-contracts/src/action-lineage.d.ts +120 -0
  19. package/dist/integration-contracts/src/action-lineage.js +208 -0
  20. package/dist/integration-contracts/src/activity-classification.d.ts +251 -0
  21. package/dist/integration-contracts/src/activity-classification.js +406 -0
  22. package/dist/integration-contracts/src/ai-execution.d.ts +62 -0
  23. package/dist/integration-contracts/src/ai-execution.js +244 -0
  24. package/dist/integration-contracts/src/ai-session.d.ts +282 -0
  25. package/dist/integration-contracts/src/ai-session.js +192 -0
  26. package/dist/integration-contracts/src/artifact-lineage.d.ts +140 -0
  27. package/dist/integration-contracts/src/artifact-lineage.js +236 -0
  28. package/dist/integration-contracts/src/lineage-validation.d.ts +14 -0
  29. package/dist/integration-contracts/src/lineage-validation.js +64 -0
  30. package/dist/integration-contracts/src/posting-lineage.d.ts +105 -0
  31. package/dist/integration-contracts/src/posting-lineage.js +147 -0
  32. package/lib/execution-capture.mjs +1 -1
  33. package/lib/session-activity.mjs +130 -0
  34. package/lib/session-titles.mjs +13 -1
  35. package/package.json +16 -25
@@ -0,0 +1,192 @@
1
+ /** Independently versioned, content-free AI session evidence and read contracts. */
2
+ export const AI_SESSION_EVIDENCE_CONTRACT_VERSION = "1.0.0";
3
+ export const AI_SESSION_EVIDENCE_CAPABILITY = "ai_session_evidence_v1";
4
+ export const AI_SESSION_EVIDENCE_LIMITS = {
5
+ maxBytes: 65_536,
6
+ maxEvidenceReferences: 32,
7
+ maxExplanationBytes: 2_048,
8
+ };
9
+ export class AiSessionContractError extends Error {
10
+ field;
11
+ code;
12
+ constructor(field, code = "invalid_payload") {
13
+ super(`Invalid AI session contract at ${field}`);
14
+ this.field = field;
15
+ this.code = code;
16
+ this.name = "AiSessionContractError";
17
+ }
18
+ }
19
+ const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
20
+ const fail = (field) => { throw new AiSessionContractError(field); };
21
+ function object(value, required, optional, path) {
22
+ if (!isObject(value))
23
+ fail(path);
24
+ const record = value;
25
+ const allowed = new Set([...required, ...optional]);
26
+ if (Object.keys(record).some((key) => !allowed.has(key)) || required.some((key) => !(key in record)))
27
+ fail(`${path}.fields`);
28
+ return record;
29
+ }
30
+ function text(value, path, max) {
31
+ if (typeof value !== "string" || value.length < 1 || value.length > max || value.trim() !== value)
32
+ fail(path);
33
+ return value;
34
+ }
35
+ function nullableText(value, path, max) {
36
+ return value === null ? null : text(value, path, max);
37
+ }
38
+ function timestamp(value, path) {
39
+ if (typeof value !== "string" || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,6})?(?:Z|[+-]\d\d:\d\d)$/.test(value) || !Number.isFinite(Date.parse(value)))
40
+ fail(path);
41
+ return value;
42
+ }
43
+ function oneOf(value, choices, path) {
44
+ if (typeof value !== "string" || !choices.includes(value))
45
+ fail(path);
46
+ return value;
47
+ }
48
+ const WORK_TYPES = ["software_delivery", "decision_support", "knowledge_output"];
49
+ const REVISION_KINDS = ["artifact", "contribution", "commit", "pull_request", "deployment", "decision", "knowledge_output", "validation", "policy", "model_comparison", "outcome"];
50
+ function evidenceRef(value, path) {
51
+ const v = object(value, ["sourceId", "sourceRecordId", "revision", "mappingVersion"], [], path);
52
+ if (typeof v.sourceId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(v.sourceId))
53
+ fail(`${path}.sourceId`);
54
+ return { sourceId: v.sourceId.toLowerCase(), sourceRecordId: text(v.sourceRecordId, `${path}.sourceRecordId`, 160), revision: text(v.revision, `${path}.revision`, 160), mappingVersion: text(v.mappingVersion, `${path}.mappingVersion`, 64) };
55
+ }
56
+ function sessionRef(value) {
57
+ const v = object(value, ["namespace", "protectedSessionKey", "mappingVersion", "segmentKey"], [], "session");
58
+ const segmentKey = nullableText(v.segmentKey, "session.segmentKey", 160);
59
+ if (segmentKey !== null)
60
+ fail("session.segmentKey");
61
+ return { namespace: text(v.namespace, "session.namespace", 64), protectedSessionKey: text(v.protectedSessionKey, "session.protectedSessionKey", 160), mappingVersion: text(v.mappingVersion, "session.mappingVersion", 64), segmentKey: null };
62
+ }
63
+ function revisionTarget(value, path) {
64
+ const v = object(value, ["kind", "reference"], [], path);
65
+ return { kind: oneOf(v.kind, REVISION_KINDS, `${path}.kind`), reference: evidenceRef(v.reference, `${path}.reference`) };
66
+ }
67
+ function refs(value, path) {
68
+ if (!Array.isArray(value) || value.length > AI_SESSION_EVIDENCE_LIMITS.maxEvidenceReferences)
69
+ fail(path);
70
+ return value.map((item, index) => evidenceRef(item, `${path}.${index}`));
71
+ }
72
+ function assertion(value) {
73
+ const v = object(value, ["kind", "state", "effectiveAt", "target", "explanation", "evidence", "predecessorId", "context"], [], "payload");
74
+ const kind = oneOf(v.kind, ["goal", "disposition", "validation", "acceptance", "model_fit", "approved_use", "reuse", "rework", "outcome"], "payload.kind");
75
+ const state = oneOf(v.state, ["positive", "negative", "partial", "unknown", "disputed", "not_applicable"], "payload.state");
76
+ const explanation = typeof v.explanation === "string" ? v.explanation : fail("payload.explanation");
77
+ if (new TextEncoder().encode(explanation).byteLength > AI_SESSION_EVIDENCE_LIMITS.maxExplanationBytes)
78
+ fail("payload.explanation");
79
+ const c = object(v.context, ["goalDisposition", "validationScope", "requiredCheck", "recipientRole", "modelId", "modelConfigurationRef", "taskRequirementsRef", "comparisonRef", "policyVersionRef", "conditionsChecked"], [], "payload.context");
80
+ const goalDisposition = c.goalDisposition === null ? null : oneOf(c.goalDisposition, ["achieved", "unmet", "partial", "useful_stop", "changed_direction"], "payload.context.goalDisposition");
81
+ const nullableRef = (name) => c[name] === null ? null : evidenceRef(c[name], `payload.context.${name}`);
82
+ for (const field of ["requiredCheck", "conditionsChecked"])
83
+ if (c[field] !== null && typeof c[field] !== "boolean")
84
+ fail(`payload.context.${field}`);
85
+ const result = {
86
+ kind, state, effectiveAt: timestamp(v.effectiveAt, "payload.effectiveAt"),
87
+ target: v.target === null ? null : revisionTarget(v.target, "payload.target"), explanation,
88
+ evidence: refs(v.evidence, "payload.evidence"),
89
+ predecessorId: v.predecessorId === null ? null : text(v.predecessorId, "payload.predecessorId", 36),
90
+ context: {
91
+ goalDisposition,
92
+ validationScope: nullableText(c.validationScope, "payload.context.validationScope", 160),
93
+ requiredCheck: c.requiredCheck,
94
+ recipientRole: nullableText(c.recipientRole, "payload.context.recipientRole", 64),
95
+ modelId: nullableText(c.modelId, "payload.context.modelId", 160),
96
+ modelConfigurationRef: nullableRef("modelConfigurationRef"),
97
+ taskRequirementsRef: nullableRef("taskRequirementsRef"),
98
+ comparisonRef: nullableRef("comparisonRef"),
99
+ policyVersionRef: nullableRef("policyVersionRef"),
100
+ conditionsChecked: c.conditionsChecked,
101
+ },
102
+ };
103
+ for (const [field, expected] of [["goalDisposition", "goalDisposition"], ["validation", "validationScope"], ["acceptance", "recipientRole"], ["model_fit", "modelId"], ["approved_use", "policyVersionRef"]]) {
104
+ if (kind === field && result.context[expected] === null)
105
+ fail(`payload.context.${expected}`);
106
+ }
107
+ if (state === "not_applicable" && explanation.length === 0)
108
+ fail("payload.explanation");
109
+ return result;
110
+ }
111
+ function membership(value) {
112
+ const v = object(value, ["targetKind", "target", "relationship", "effectiveAt"], [], "payload");
113
+ const targetKind = oneOf(v.targetKind, ["completion", "action", "work_context", "parent", "fork", "equivalent_session"], "payload.targetKind");
114
+ const relationship = oneOf(v.relationship, ["member", "parent", "fork", "equivalent"], "payload.relationship");
115
+ const expected = targetKind === "parent" ? "parent" : targetKind === "fork" ? "fork" : targetKind === "equivalent_session" ? "equivalent" : "member";
116
+ if (relationship !== expected)
117
+ fail("payload.relationship");
118
+ return { targetKind, target: evidenceRef(v.target, "payload.target"), relationship, effectiveAt: timestamp(v.effectiveAt, "payload.effectiveAt") };
119
+ }
120
+ function lifecycle(value) {
121
+ const v = object(value, ["workType", "stage", "from", "to", "environment", "inclusionEvidence", "transformationEvidence", "effectiveAt", "predecessorId"], [], "payload");
122
+ const workType = oneOf(v.workType, WORK_TYPES, "payload.workType");
123
+ const stage = oneOf(v.stage, ["durable_output", "committed", "pr_included", "merged", "deployed", "finding", "reviewed", "accepted_decision", "acted_disposition", "published", "reused"], "payload.stage");
124
+ const valid = workType === "software_delivery" ? ["durable_output", "committed", "pr_included", "merged", "deployed"] : workType === "decision_support" ? ["finding", "reviewed", "accepted_decision", "acted_disposition"] : ["durable_output", "reviewed", "published", "reused"];
125
+ if (!valid.includes(stage))
126
+ fail("payload.stage");
127
+ const evidence = refs(v.inclusionEvidence, "payload.inclusionEvidence");
128
+ const transformationEvidence = v.transformationEvidence === null ? null : evidenceRef(v.transformationEvidence, "payload.transformationEvidence");
129
+ if (workType === "software_delivery" && stage !== "durable_output" && evidence.length === 0)
130
+ fail("payload.inclusionEvidence");
131
+ if (stage === "deployed" && v.environment === null)
132
+ fail("payload.environment");
133
+ return {
134
+ workType, stage, from: revisionTarget(v.from, "payload.from"), to: revisionTarget(v.to, "payload.to"),
135
+ environment: nullableText(v.environment, "payload.environment", 64), inclusionEvidence: evidence,
136
+ transformationEvidence, effectiveAt: timestamp(v.effectiveAt, "payload.effectiveAt"),
137
+ predecessorId: v.predecessorId === null ? null : text(v.predecessorId, "payload.predecessorId", 36),
138
+ };
139
+ }
140
+ /** Parse an already-decoded packet. Use parseAiSessionEvidenceBody at an HTTP boundary for byte limits. */
141
+ export function parseAiSessionEvidencePacket(input) {
142
+ const v = object(input, ["contractVersion", "reportId", "session", "occurredAt", "kind", "payload"], [], "packet");
143
+ if (v.contractVersion !== AI_SESSION_EVIDENCE_CONTRACT_VERSION)
144
+ fail("packet.contractVersion");
145
+ const kind = oneOf(v.kind, ["membership", "assertion", "lifecycle"], "packet.kind");
146
+ const result = {
147
+ contractVersion: AI_SESSION_EVIDENCE_CONTRACT_VERSION,
148
+ reportId: text(v.reportId, "packet.reportId", 160),
149
+ session: sessionRef(v.session),
150
+ occurredAt: timestamp(v.occurredAt, "packet.occurredAt"),
151
+ kind,
152
+ payload: kind === "membership" ? membership(v.payload) : kind === "assertion" ? assertion(v.payload) : lifecycle(v.payload),
153
+ };
154
+ const refsCount = countPacketReferences(result);
155
+ if (refsCount > AI_SESSION_EVIDENCE_LIMITS.maxEvidenceReferences)
156
+ fail("packet.evidenceReferences");
157
+ return result;
158
+ }
159
+ /** Build and validate a v1 evidence packet before handing it to an enrolled sender. */
160
+ export function buildAiSessionEvidencePacket(input) {
161
+ return parseAiSessionEvidencePacket({ ...input, contractVersion: AI_SESSION_EVIDENCE_CONTRACT_VERSION });
162
+ }
163
+ /** Build a whole-session membership report. V1 intentionally has no segment argument. */
164
+ export function buildAiSessionMembershipPacket(input) {
165
+ return buildAiSessionEvidencePacket({ ...input, kind: "membership" });
166
+ }
167
+ function countPacketReferences(packet) {
168
+ const count = (v) => {
169
+ if (Array.isArray(v))
170
+ return v.reduce((n, item) => n + count(item), 0);
171
+ if (!isObject(v))
172
+ return 0;
173
+ if ("sourceId" in v && "sourceRecordId" in v && "revision" in v && "mappingVersion" in v)
174
+ return 1;
175
+ return Object.values(v).reduce((n, item) => n + count(item), 0);
176
+ };
177
+ return count(packet.payload);
178
+ }
179
+ /** Enforce the wire byte cap before JSON parsing and then apply strict structural validation. */
180
+ export function parseAiSessionEvidenceBody(raw) {
181
+ if (new TextEncoder().encode(raw).byteLength > AI_SESSION_EVIDENCE_LIMITS.maxBytes) {
182
+ throw new AiSessionContractError("packet", "payload_too_large");
183
+ }
184
+ let parsed;
185
+ try {
186
+ parsed = JSON.parse(raw);
187
+ }
188
+ catch {
189
+ fail("packet.json");
190
+ }
191
+ return parseAiSessionEvidencePacket(parsed);
192
+ }
@@ -0,0 +1,140 @@
1
+ export declare const ARTIFACT_LINEAGE_CONTRACT_VERSION: "1.0.0";
2
+ export type ArtifactKind = "commit" | "pull_request" | "linear_ticket" | "persisted_tool_result";
3
+ export type ArtifactRelationship = "created" | "modified" | "read" | "referenced";
4
+ export type ArtifactObservationOperation = ArtifactRelationship | "snapshot" | "deleted";
5
+ export type LinkQualification = "instrumented" | "source_confirmed" | "reviewed" | "inferred";
6
+ /** Supplied by authenticated enrollment/server authority, never by an action payload. */
7
+ export type LineageOwningScopeV1 = {
8
+ kind: "tenant";
9
+ } | {
10
+ kind: "team";
11
+ teamId: string;
12
+ } | {
13
+ kind: "project";
14
+ projectId: string;
15
+ };
16
+ export interface LineageAuthorityV1 {
17
+ tenantId: string;
18
+ sourceId: string;
19
+ owningScope: LineageOwningScopeV1;
20
+ }
21
+ export interface IntegrityDigestV1 {
22
+ algorithm: "sha256";
23
+ value: string;
24
+ }
25
+ export type ArtifactLocatorV1 = {
26
+ kind: "source_reference";
27
+ reference: string;
28
+ } | {
29
+ kind: "https";
30
+ url: string;
31
+ };
32
+ export type ArtifactIdentityV1 = {
33
+ kind: "commit";
34
+ repository: {
35
+ provider: "github" | "local";
36
+ repositoryId: string;
37
+ };
38
+ sha: string;
39
+ } | {
40
+ kind: "pull_request";
41
+ repositoryId: string;
42
+ pullRequestId: string;
43
+ } | {
44
+ kind: "linear_ticket";
45
+ workspaceId: string;
46
+ issueId: string;
47
+ } | {
48
+ kind: "persisted_tool_result";
49
+ persisted: true;
50
+ resultId: string | null;
51
+ integrity: IntegrityDigestV1 | null;
52
+ locator: ArtifactLocatorV1;
53
+ subtype: "report" | "document" | "other";
54
+ };
55
+ export interface ArtifactRevisionV1 {
56
+ sourceRevisionId: string | null;
57
+ headCommitSha: string | null;
58
+ integrity: IntegrityDigestV1 | null;
59
+ }
60
+ /** Independent evidence keys: a provider delivery is not an action or a ledger record. */
61
+ export interface LineageEvidenceReferenceV1 {
62
+ sourceId: string;
63
+ sourceRecordId: string;
64
+ mappingVersion: string;
65
+ }
66
+ export interface DurableArtifactV1 {
67
+ contractVersion: typeof ARTIFACT_LINEAGE_CONTRACT_VERSION;
68
+ artifactId: string;
69
+ authority: LineageAuthorityV1;
70
+ identity: ArtifactIdentityV1;
71
+ immutability: "immutable" | "mutable";
72
+ availability: "unknown" | "available" | "unavailable";
73
+ availabilityVerifiedAt: string | null;
74
+ recordedAt: string;
75
+ }
76
+ export interface ArtifactObservationV1 {
77
+ contractVersion: typeof ARTIFACT_LINEAGE_CONTRACT_VERSION;
78
+ observationId: string;
79
+ artifactId: string;
80
+ authority: LineageAuthorityV1;
81
+ sourceChangeId: string;
82
+ deliveryId: string | null;
83
+ operation: ArtifactObservationOperation;
84
+ revision: ArtifactRevisionV1;
85
+ beforeRevision: ArtifactRevisionV1 | null;
86
+ occurredAt: string | null;
87
+ receivedAt: string;
88
+ recordedAt: string;
89
+ evidence: LineageEvidenceReferenceV1;
90
+ }
91
+ export interface LinkAuditV1 {
92
+ predecessorLinkId: string | null;
93
+ /** Null when reviewer identity is unknown or current principal-view authority does not allow disclosure. */
94
+ reviewerPrincipalId: string | null;
95
+ reason: string;
96
+ effectiveAt: string;
97
+ }
98
+ export interface QualifiedEventArtifactLinkV1 {
99
+ contractVersion: typeof ARTIFACT_LINEAGE_CONTRACT_VERSION;
100
+ linkId: string;
101
+ tenantId: string;
102
+ /** Composite (tenantId, recordId) targets the exact canonical ledger evidence version. */
103
+ event: {
104
+ tenantId: string;
105
+ recordId: string;
106
+ };
107
+ artifactId: string;
108
+ observationId: string | null;
109
+ relationship: ArtifactRelationship;
110
+ assertionOrigin: "instrumentation" | "provider" | "review" | "inference";
111
+ qualification: LinkQualification;
112
+ /** Source confirmation must match producing-action evidence, not just artifact existence. */
113
+ supportingEvidence: LineageEvidenceReferenceV1[];
114
+ audit: LinkAuditV1 | null;
115
+ recordedAt: string;
116
+ }
117
+ export interface NativeArtifactRelationshipV1 {
118
+ contractVersion: typeof ARTIFACT_LINEAGE_CONTRACT_VERSION;
119
+ relationshipId: string;
120
+ tenantId: string;
121
+ kind: "commit_in_pull_request";
122
+ fromArtifactId: string;
123
+ toArtifactId: string;
124
+ supportingEvidence: LineageEvidenceReferenceV1[];
125
+ recordedAt: string;
126
+ }
127
+ export declare function parseLineageAuthority(value: unknown): LineageAuthorityV1;
128
+ export declare function parseIntegrity(value: unknown): IntegrityDigestV1;
129
+ /** Approved origins come from server/source configuration. A locator authorizes no fetch. */
130
+ export declare function parseArtifactIdentity(value: unknown, approvedLocatorOrigins?: readonly string[]): ArtifactIdentityV1;
131
+ export declare function parseArtifactRevision(value: unknown): ArtifactRevisionV1;
132
+ export declare function parseEvidenceReference(value: unknown): LineageEvidenceReferenceV1;
133
+ /** JSON tuple encoding is unambiguous even when opaque IDs contain delimiters. */
134
+ export declare function artifactIdentityKey(identity: ArtifactIdentityV1, authority: LineageAuthorityV1): string;
135
+ export declare function observationIdentityKey(observation: ArtifactObservationV1): string;
136
+ export declare function parseDurableArtifact(value: unknown, approvedLocatorOrigins?: readonly string[]): DurableArtifactV1;
137
+ export declare function parseArtifactObservation(value: unknown, artifactKind: ArtifactKind): ArtifactObservationV1;
138
+ /** Validates evidence shape only. Database authority must check every referenced endpoint. */
139
+ export declare function validateEventArtifactLink(link: QualifiedEventArtifactLinkV1): void;
140
+ export declare function validateNativeArtifactRelationship(relation: NativeArtifactRelationshipV1): void;
@@ -0,0 +1,236 @@
1
+ import { choice, fail, fields, id, nullable, sha, timestamp, uuid, version } from "./lineage-validation.js";
2
+ export const ARTIFACT_LINEAGE_CONTRACT_VERSION = "1.0.0";
3
+ export function parseLineageAuthority(value) {
4
+ const a = fields(value, ["tenantId", "sourceId", "owningScope"], "authority");
5
+ const s = fields(a.owningScope, ["kind", "teamId", "projectId"], "authority.owningScope");
6
+ let owningScope;
7
+ if (s.kind === "tenant") {
8
+ fields(s, ["kind"], "authority.owningScope");
9
+ owningScope = { kind: "tenant" };
10
+ }
11
+ else if (s.kind === "team") {
12
+ fields(s, ["kind", "teamId"], "authority.owningScope");
13
+ owningScope = { kind: "team", teamId: uuid(s.teamId, "authority.owningScope.teamId") };
14
+ }
15
+ else {
16
+ fields(s, ["kind", "projectId"], "authority.owningScope");
17
+ if (s.kind !== "project")
18
+ fail("authority.owningScope.kind");
19
+ owningScope = { kind: "project", projectId: uuid(s.projectId, "authority.owningScope.projectId") };
20
+ }
21
+ return {
22
+ tenantId: uuid(a.tenantId, "authority.tenantId"),
23
+ sourceId: uuid(a.sourceId, "authority.sourceId"),
24
+ owningScope,
25
+ };
26
+ }
27
+ export function parseIntegrity(value) {
28
+ const d = fields(value, ["algorithm", "value"], "integrity");
29
+ if (d.algorithm !== "sha256" || typeof d.value !== "string" || !/^[0-9a-f]{64}$/i.test(d.value)) {
30
+ fail("integrity");
31
+ }
32
+ return { algorithm: "sha256", value: d.value.toLowerCase() };
33
+ }
34
+ /** Approved origins come from server/source configuration. A locator authorizes no fetch. */
35
+ export function parseArtifactIdentity(value, approvedLocatorOrigins = []) {
36
+ const root = fields(value, [
37
+ "kind", "repository", "sha", "repositoryId", "pullRequestId", "workspaceId",
38
+ "issueId", "persisted", "resultId", "integrity", "locator", "subtype",
39
+ ], "artifact");
40
+ const kind = choice(root.kind, ["commit", "pull_request", "linear_ticket", "persisted_tool_result"], "artifact.kind");
41
+ if (kind === "commit") {
42
+ const c = fields(value, ["kind", "repository", "sha"], "artifact");
43
+ const r = fields(c.repository, ["provider", "repositoryId"], "artifact.repository");
44
+ const provider = choice(r.provider, ["github", "local"], "artifact.repository.provider");
45
+ const repositoryId = provider === "github"
46
+ ? numericProviderId(r.repositoryId, "artifact.repository.repositoryId")
47
+ : id(r.repositoryId, "artifact.repository.repositoryId");
48
+ return { kind, repository: { provider, repositoryId }, sha: sha(c.sha, "artifact.sha") };
49
+ }
50
+ if (kind === "pull_request") {
51
+ const p = fields(value, ["kind", "repositoryId", "pullRequestId"], "artifact");
52
+ return {
53
+ kind,
54
+ repositoryId: numericProviderId(p.repositoryId, "artifact.repositoryId"),
55
+ pullRequestId: numericProviderId(p.pullRequestId, "artifact.pullRequestId"),
56
+ };
57
+ }
58
+ if (kind === "linear_ticket") {
59
+ const t = fields(value, ["kind", "workspaceId", "issueId"], "artifact");
60
+ return { kind, workspaceId: uuid(t.workspaceId, "artifact.workspaceId"), issueId: uuid(t.issueId, "artifact.issueId") };
61
+ }
62
+ const r = fields(value, ["kind", "persisted", "resultId", "integrity", "locator", "subtype"], "artifact");
63
+ if (r.persisted !== true)
64
+ fail("artifact.persisted");
65
+ const resultId = nullable(r.resultId, (v) => id(v, "artifact.resultId"));
66
+ const integrity = nullable(r.integrity, parseIntegrity);
67
+ if (resultId === null && integrity === null)
68
+ fail("artifact.identity");
69
+ const l = fields(r.locator, ["kind", "reference", "url"], "artifact.locator");
70
+ let locator;
71
+ if (l.kind === "source_reference") {
72
+ fields(r.locator, ["kind", "reference"], "artifact.locator");
73
+ locator = { kind: "source_reference", reference: id(l.reference, "artifact.locator.reference") };
74
+ }
75
+ else {
76
+ fields(r.locator, ["kind", "url"], "artifact.locator");
77
+ if (l.kind !== "https" || typeof l.url !== "string" || l.url.length > 1024)
78
+ fail("artifact.locator");
79
+ let url;
80
+ try {
81
+ url = new URL(l.url);
82
+ }
83
+ catch {
84
+ fail("artifact.locator.url");
85
+ }
86
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash ||
87
+ !approvedLocatorOrigins.includes(url.origin))
88
+ fail("artifact.locator.url");
89
+ locator = { kind: "https", url: url.href };
90
+ }
91
+ return { kind, persisted: true, resultId, integrity, locator, subtype: choice(r.subtype, ["report", "document", "other"], "artifact.subtype") };
92
+ }
93
+ function numericProviderId(value, path) {
94
+ if (typeof value !== "string" || !/^[1-9]\d{0,29}$/.test(value))
95
+ fail(path);
96
+ return value;
97
+ }
98
+ export function parseArtifactRevision(value) {
99
+ const r = fields(value, ["sourceRevisionId", "headCommitSha", "integrity"], "revision");
100
+ return {
101
+ sourceRevisionId: nullable(r.sourceRevisionId, (v) => id(v, "revision.sourceRevisionId")),
102
+ headCommitSha: nullable(r.headCommitSha, (v) => sha(v, "revision.headCommitSha")),
103
+ integrity: nullable(r.integrity, parseIntegrity),
104
+ };
105
+ }
106
+ export function parseEvidenceReference(value) {
107
+ const e = fields(value, ["sourceId", "sourceRecordId", "mappingVersion"], "evidence");
108
+ return {
109
+ sourceId: uuid(e.sourceId, "evidence.sourceId"),
110
+ sourceRecordId: id(e.sourceRecordId, "evidence.sourceRecordId"),
111
+ mappingVersion: version(e.mappingVersion, "evidence.mappingVersion"),
112
+ };
113
+ }
114
+ /** JSON tuple encoding is unambiguous even when opaque IDs contain delimiters. */
115
+ export function artifactIdentityKey(identity, authority) {
116
+ const a = parseLineageAuthority(authority);
117
+ let resource;
118
+ switch (identity.kind) {
119
+ case "commit":
120
+ resource = [identity.kind, identity.repository.provider,
121
+ identity.repository.provider === "local" ? a.sourceId : null,
122
+ identity.repository.repositoryId, identity.sha.toLowerCase()];
123
+ break;
124
+ case "pull_request":
125
+ resource = [identity.kind, "github.com", identity.repositoryId, identity.pullRequestId];
126
+ break;
127
+ case "linear_ticket":
128
+ resource = [identity.kind, identity.workspaceId.toLowerCase(), identity.issueId.toLowerCase()];
129
+ break;
130
+ case "persisted_tool_result":
131
+ resource = [identity.kind, a.sourceId, identity.resultId === null ? "digest" : "result_id",
132
+ identity.resultId ?? (identity.integrity?.value.toLowerCase() ?? fail("artifact.identity"))];
133
+ }
134
+ return JSON.stringify([ARTIFACT_LINEAGE_CONTRACT_VERSION, a.tenantId, ...resource]);
135
+ }
136
+ export function observationIdentityKey(observation) {
137
+ return JSON.stringify([ARTIFACT_LINEAGE_CONTRACT_VERSION,
138
+ observation.authority.tenantId, observation.authority.sourceId, observation.artifactId,
139
+ observation.sourceChangeId]);
140
+ }
141
+ export function parseDurableArtifact(value, approvedLocatorOrigins = []) {
142
+ const d = fields(value, ["contractVersion", "artifactId", "authority", "identity", "immutability",
143
+ "availability", "availabilityVerifiedAt", "recordedAt"], "durableArtifact");
144
+ if (d.contractVersion !== ARTIFACT_LINEAGE_CONTRACT_VERSION)
145
+ fail("durableArtifact.contractVersion");
146
+ const identity = parseArtifactIdentity(d.identity, approvedLocatorOrigins);
147
+ const immutability = identity.kind === "commit" ||
148
+ (identity.kind === "persisted_tool_result" && identity.resultId === null) ? "immutable" : "mutable";
149
+ if (d.immutability !== immutability)
150
+ fail("durableArtifact.immutability");
151
+ return {
152
+ contractVersion: ARTIFACT_LINEAGE_CONTRACT_VERSION,
153
+ artifactId: uuid(d.artifactId, "durableArtifact.artifactId"),
154
+ authority: parseLineageAuthority(d.authority), identity, immutability,
155
+ availability: choice(d.availability, ["unknown", "available", "unavailable"], "durableArtifact.availability"),
156
+ availabilityVerifiedAt: nullable(d.availabilityVerifiedAt, (v) => timestamp(v, "durableArtifact.availabilityVerifiedAt")),
157
+ recordedAt: timestamp(d.recordedAt, "durableArtifact.recordedAt"),
158
+ };
159
+ }
160
+ export function parseArtifactObservation(value, artifactKind) {
161
+ const o = fields(value, ["contractVersion", "observationId", "artifactId", "authority",
162
+ "sourceChangeId", "deliveryId", "operation", "revision", "beforeRevision",
163
+ "occurredAt", "receivedAt", "recordedAt", "evidence"], "observation");
164
+ if (o.contractVersion !== ARTIFACT_LINEAGE_CONTRACT_VERSION)
165
+ fail("observation.contractVersion");
166
+ const authority = parseLineageAuthority(o.authority);
167
+ const evidence = parseEvidenceReference(o.evidence);
168
+ if (authority.sourceId !== evidence.sourceId)
169
+ fail("observation.evidence.sourceId");
170
+ const operation = choice(o.operation, ["created", "modified", "read", "referenced", "snapshot", "deleted"], "observation.operation");
171
+ if (artifactKind === "commit" && (operation === "modified" || operation === "deleted"))
172
+ fail("observation.operation");
173
+ return {
174
+ contractVersion: ARTIFACT_LINEAGE_CONTRACT_VERSION,
175
+ observationId: uuid(o.observationId, "observation.observationId"),
176
+ artifactId: uuid(o.artifactId, "observation.artifactId"),
177
+ authority, sourceChangeId: id(o.sourceChangeId, "observation.sourceChangeId"),
178
+ deliveryId: nullable(o.deliveryId, (v) => id(v, "observation.deliveryId")),
179
+ operation, revision: parseArtifactRevision(o.revision),
180
+ beforeRevision: nullable(o.beforeRevision, parseArtifactRevision),
181
+ occurredAt: nullable(o.occurredAt, (v) => timestamp(v, "observation.occurredAt")),
182
+ receivedAt: timestamp(o.receivedAt, "observation.receivedAt"),
183
+ recordedAt: timestamp(o.recordedAt, "observation.recordedAt"), evidence,
184
+ };
185
+ }
186
+ /** Validates evidence shape only. Database authority must check every referenced endpoint. */
187
+ export function validateEventArtifactLink(link) {
188
+ if (link.contractVersion !== ARTIFACT_LINEAGE_CONTRACT_VERSION)
189
+ fail("link.contractVersion");
190
+ uuid(link.linkId, "link.linkId");
191
+ uuid(link.artifactId, "link.artifactId");
192
+ if (uuid(link.tenantId, "link.tenantId") !== uuid(link.event.tenantId, "link.event.tenantId"))
193
+ fail("link.event.tenantId");
194
+ uuid(link.event.recordId, "link.event.recordId");
195
+ if (link.observationId !== null)
196
+ uuid(link.observationId, "link.observationId");
197
+ choice(link.relationship, ["created", "modified", "read", "referenced"], "link.relationship");
198
+ const origin = choice(link.assertionOrigin, ["instrumentation", "provider", "review", "inference"], "link.assertionOrigin");
199
+ const qualification = choice(link.qualification, ["instrumented", "source_confirmed", "reviewed", "inferred"], "link.qualification");
200
+ if ((qualification === "instrumented" && origin !== "instrumentation") ||
201
+ (qualification === "reviewed" && origin !== "review") ||
202
+ (qualification === "inferred" && origin !== "inference") ||
203
+ (qualification === "source_confirmed" && origin !== "provider" && origin !== "instrumentation"))
204
+ fail("link.qualification");
205
+ if (link.supportingEvidence.length < 1 || link.supportingEvidence.length > 8)
206
+ fail("link.supportingEvidence");
207
+ link.supportingEvidence.forEach(parseEvidenceReference);
208
+ if (qualification === "reviewed" && link.audit === null)
209
+ fail("link.audit");
210
+ if (link.audit !== null) {
211
+ const audit = fields(link.audit, ["predecessorLinkId", "reviewerPrincipalId", "reason", "effectiveAt"], "link.audit");
212
+ if (audit.predecessorLinkId !== null) {
213
+ if (uuid(audit.predecessorLinkId, "link.audit.predecessorLinkId") === link.linkId)
214
+ fail("link.audit.predecessorLinkId");
215
+ }
216
+ nullable(audit.reviewerPrincipalId, (v) => uuid(v, "link.audit.reviewerPrincipalId"));
217
+ if (typeof audit.reason !== "string" || !audit.reason.trim() || audit.reason.length > 512)
218
+ fail("link.audit.reason");
219
+ timestamp(audit.effectiveAt, "link.audit.effectiveAt");
220
+ }
221
+ timestamp(link.recordedAt, "link.recordedAt");
222
+ }
223
+ export function validateNativeArtifactRelationship(relation) {
224
+ if (relation.contractVersion !== ARTIFACT_LINEAGE_CONTRACT_VERSION || relation.kind !== "commit_in_pull_request")
225
+ fail("relation.contractVersion");
226
+ uuid(relation.relationshipId, "relation.relationshipId");
227
+ uuid(relation.tenantId, "relation.tenantId");
228
+ uuid(relation.fromArtifactId, "relation.fromArtifactId");
229
+ uuid(relation.toArtifactId, "relation.toArtifactId");
230
+ if (relation.fromArtifactId === relation.toArtifactId)
231
+ fail("relation.toArtifactId");
232
+ if (relation.supportingEvidence.length < 1 || relation.supportingEvidence.length > 8)
233
+ fail("relation.supportingEvidence");
234
+ relation.supportingEvidence.forEach(parseEvidenceReference);
235
+ timestamp(relation.recordedAt, "relation.recordedAt");
236
+ }
@@ -0,0 +1,14 @@
1
+ /** Strict, content-free wire validation. Errors contain field paths, never values. */
2
+ export declare class LineageContractError extends Error {
3
+ readonly field: string;
4
+ constructor(field: string);
5
+ }
6
+ export declare function fail(field: string): never;
7
+ export declare function fields(value: unknown, allowed: readonly string[], path: string): Record<string, unknown>;
8
+ export declare function id(value: unknown, path: string): string;
9
+ export declare function uuid(value: unknown, path: string): string;
10
+ export declare function choice<T extends string>(value: unknown, values: readonly T[], path: string): T;
11
+ export declare function timestamp(value: unknown, path: string): string;
12
+ export declare function nullable<T>(value: unknown, parse: (value: unknown) => T): T | null;
13
+ export declare function version(value: unknown, path: string): string;
14
+ export declare function sha(value: unknown, path: string): string;
@@ -0,0 +1,64 @@
1
+ /** Strict, content-free wire validation. Errors contain field paths, never values. */
2
+ export class LineageContractError extends Error {
3
+ field;
4
+ constructor(field) {
5
+ super("Invalid lineage field: " + field);
6
+ this.field = field;
7
+ this.name = "LineageContractError";
8
+ }
9
+ }
10
+ export function fail(field) {
11
+ throw new LineageContractError(field);
12
+ }
13
+ export function fields(value, allowed, path) {
14
+ if (!value || typeof value !== "object" || Array.isArray(value))
15
+ fail(path);
16
+ const record = value;
17
+ if (Object.keys(record).some((key) => !allowed.includes(key)))
18
+ fail(path + ".fields");
19
+ return record;
20
+ }
21
+ export function id(value, path) {
22
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value)) {
23
+ fail(path);
24
+ }
25
+ return value;
26
+ }
27
+ // PostgreSQL UUID columns also contain deterministic fixture identifiers without RFC version bits.
28
+ export function uuid(value, path) {
29
+ if (typeof value !== "string" ||
30
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {
31
+ fail(path);
32
+ }
33
+ return value.toLowerCase();
34
+ }
35
+ export function choice(value, values, path) {
36
+ if (typeof value !== "string" || !values.includes(value))
37
+ fail(path);
38
+ return value;
39
+ }
40
+ export function timestamp(value, path) {
41
+ if (typeof value !== "string")
42
+ fail(path);
43
+ const match = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/.exec(value);
44
+ if (!match || !Number.isFinite(Date.parse(value)))
45
+ fail(path);
46
+ // Validate the written calendar fields before applying a timezone offset.
47
+ // Date.parse otherwise normalizes invalid dates such as February 30.
48
+ if (new Date(`${match[1]}Z`).toISOString().slice(0, 19) !== match[1])
49
+ fail(path);
50
+ return new Date(value).toISOString();
51
+ }
52
+ export function nullable(value, parse) {
53
+ return value === null ? null : parse(value);
54
+ }
55
+ export function version(value, path) {
56
+ if (typeof value !== "string" || !/^\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(value))
57
+ fail(path);
58
+ return value;
59
+ }
60
+ export function sha(value, path) {
61
+ if (typeof value !== "string" || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(value))
62
+ fail(path);
63
+ return value.toLowerCase();
64
+ }