@aryam/fixmap-core 0.9.0 → 0.9.2

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 (194) hide show
  1. package/README.md +51 -1
  2. package/dist/annotation-store.d.ts +5 -0
  3. package/dist/annotation-store.js +117 -0
  4. package/dist/annotation-store.js.map +1 -0
  5. package/dist/annotations.d.ts +57 -0
  6. package/dist/annotations.js +221 -0
  7. package/dist/annotations.js.map +1 -0
  8. package/dist/architecture-history.d.ts +33 -0
  9. package/dist/architecture-history.js +234 -0
  10. package/dist/architecture-history.js.map +1 -0
  11. package/dist/architecture.d.ts +124 -0
  12. package/dist/architecture.js +348 -0
  13. package/dist/architecture.js.map +1 -0
  14. package/dist/artifacts.d.ts +9 -0
  15. package/dist/artifacts.js +82 -0
  16. package/dist/artifacts.js.map +1 -0
  17. package/dist/ask.d.ts +48 -0
  18. package/dist/ask.js +182 -0
  19. package/dist/ask.js.map +1 -0
  20. package/dist/browser.d.ts +66 -3
  21. package/dist/browser.js +34 -2
  22. package/dist/browser.js.map +1 -1
  23. package/dist/capabilities.d.ts +39 -0
  24. package/dist/capabilities.js +172 -0
  25. package/dist/capabilities.js.map +1 -0
  26. package/dist/capability-history.d.ts +49 -0
  27. package/dist/capability-history.js +176 -0
  28. package/dist/capability-history.js.map +1 -0
  29. package/dist/change-conflicts.d.ts +34 -0
  30. package/dist/change-conflicts.js +140 -0
  31. package/dist/change-conflicts.js.map +1 -0
  32. package/dist/change-scope.d.ts +81 -0
  33. package/dist/change-scope.js +316 -0
  34. package/dist/change-scope.js.map +1 -0
  35. package/dist/characterization.d.ts +61 -0
  36. package/dist/characterization.js +169 -0
  37. package/dist/characterization.js.map +1 -0
  38. package/dist/ci-matrix.d.ts +53 -0
  39. package/dist/ci-matrix.js +170 -0
  40. package/dist/ci-matrix.js.map +1 -0
  41. package/dist/compare.js +2 -2
  42. package/dist/compare.js.map +1 -1
  43. package/dist/composer-projects.d.ts +32 -0
  44. package/dist/composer-projects.js +246 -0
  45. package/dist/composer-projects.js.map +1 -0
  46. package/dist/context.d.ts +1 -1
  47. package/dist/context.js +26 -4
  48. package/dist/context.js.map +1 -1
  49. package/dist/contracts.d.ts +75 -0
  50. package/dist/contracts.js +526 -0
  51. package/dist/contracts.js.map +1 -0
  52. package/dist/custom-language-context.d.ts +43 -0
  53. package/dist/custom-language-context.js +89 -0
  54. package/dist/custom-language-context.js.map +1 -0
  55. package/dist/decisions.d.ts +64 -0
  56. package/dist/decisions.js +338 -0
  57. package/dist/decisions.js.map +1 -0
  58. package/dist/dossier.d.ts +63 -0
  59. package/dist/dossier.js +176 -0
  60. package/dist/dossier.js.map +1 -0
  61. package/dist/dotnet-projects.d.ts +26 -0
  62. package/dist/dotnet-projects.js +171 -0
  63. package/dist/dotnet-projects.js.map +1 -0
  64. package/dist/editor-loader.d.ts +9 -0
  65. package/dist/editor-loader.js +18 -0
  66. package/dist/editor-loader.js.map +1 -0
  67. package/dist/editor-protocol.d.ts +35 -0
  68. package/dist/editor-protocol.js +200 -0
  69. package/dist/editor-protocol.js.map +1 -0
  70. package/dist/editor-session.d.ts +15 -0
  71. package/dist/editor-session.js +27 -0
  72. package/dist/editor-session.js.map +1 -0
  73. package/dist/editor-transport.d.ts +10 -0
  74. package/dist/editor-transport.js +75 -0
  75. package/dist/editor-transport.js.map +1 -0
  76. package/dist/enterprise-policy.d.ts +82 -0
  77. package/dist/enterprise-policy.js +170 -0
  78. package/dist/enterprise-policy.js.map +1 -0
  79. package/dist/evidence-bundle.d.ts +13 -0
  80. package/dist/evidence-bundle.js +105 -0
  81. package/dist/evidence-bundle.js.map +1 -0
  82. package/dist/evidence.d.ts +125 -0
  83. package/dist/evidence.js +252 -0
  84. package/dist/evidence.js.map +1 -0
  85. package/dist/explain.js +7 -0
  86. package/dist/explain.js.map +1 -1
  87. package/dist/go-projects.d.ts +22 -0
  88. package/dist/go-projects.js +146 -0
  89. package/dist/go-projects.js.map +1 -0
  90. package/dist/graph.js +9 -0
  91. package/dist/graph.js.map +1 -1
  92. package/dist/grounding.d.ts +4 -1
  93. package/dist/grounding.js +70 -13
  94. package/dist/grounding.js.map +1 -1
  95. package/dist/identity-graph.d.ts +106 -0
  96. package/dist/identity-graph.js +353 -0
  97. package/dist/identity-graph.js.map +1 -0
  98. package/dist/impact.d.ts +2 -1
  99. package/dist/impact.js +12 -4
  100. package/dist/impact.js.map +1 -1
  101. package/dist/import-graph.d.ts +7 -1
  102. package/dist/import-graph.js +616 -34
  103. package/dist/import-graph.js.map +1 -1
  104. package/dist/incident.d.ts +74 -0
  105. package/dist/incident.js +212 -0
  106. package/dist/incident.js.map +1 -0
  107. package/dist/index.d.ts +91 -4
  108. package/dist/index.js +47 -3
  109. package/dist/index.js.map +1 -1
  110. package/dist/language-adapters.d.ts +33 -0
  111. package/dist/language-adapters.js +390 -0
  112. package/dist/language-adapters.js.map +1 -0
  113. package/dist/language-registry.d.ts +26 -0
  114. package/dist/language-registry.js +57 -0
  115. package/dist/language-registry.js.map +1 -0
  116. package/dist/languages.d.ts +20 -5
  117. package/dist/languages.js +197 -19
  118. package/dist/languages.js.map +1 -1
  119. package/dist/markdown.d.ts +1 -0
  120. package/dist/markdown.js +7 -1
  121. package/dist/markdown.js.map +1 -1
  122. package/dist/migration.d.ts +56 -0
  123. package/dist/migration.js +154 -0
  124. package/dist/migration.js.map +1 -0
  125. package/dist/outcomes.d.ts +57 -0
  126. package/dist/outcomes.js +146 -0
  127. package/dist/outcomes.js.map +1 -0
  128. package/dist/ownership.d.ts +29 -0
  129. package/dist/ownership.js +189 -0
  130. package/dist/ownership.js.map +1 -0
  131. package/dist/plan-alternatives.d.ts +74 -0
  132. package/dist/plan-alternatives.js +205 -0
  133. package/dist/plan-alternatives.js.map +1 -0
  134. package/dist/plan.d.ts +7 -0
  135. package/dist/plan.js +41 -8
  136. package/dist/plan.js.map +1 -1
  137. package/dist/rank.d.ts +64 -1
  138. package/dist/rank.js +278 -26
  139. package/dist/rank.js.map +1 -1
  140. package/dist/repo-scan.d.ts +8 -1
  141. package/dist/repo-scan.js +341 -97
  142. package/dist/repo-scan.js.map +1 -1
  143. package/dist/report.d.ts +16 -0
  144. package/dist/report.js +298 -33
  145. package/dist/report.js.map +1 -1
  146. package/dist/retrieval.d.ts +37 -0
  147. package/dist/retrieval.js +150 -21
  148. package/dist/retrieval.js.map +1 -1
  149. package/dist/reverse-docs.d.ts +46 -0
  150. package/dist/reverse-docs.js +179 -0
  151. package/dist/reverse-docs.js.map +1 -0
  152. package/dist/ruby-projects.d.ts +20 -0
  153. package/dist/ruby-projects.js +114 -0
  154. package/dist/ruby-projects.js.map +1 -0
  155. package/dist/runtime-evidence.d.ts +90 -0
  156. package/dist/runtime-evidence.js +186 -0
  157. package/dist/runtime-evidence.js.map +1 -0
  158. package/dist/rust-projects.d.ts +17 -0
  159. package/dist/rust-projects.js +125 -0
  160. package/dist/rust-projects.js.map +1 -0
  161. package/dist/sandbox.d.ts +59 -0
  162. package/dist/sandbox.js +202 -0
  163. package/dist/sandbox.js.map +1 -0
  164. package/dist/semantic-cache.d.ts +8 -0
  165. package/dist/semantic-cache.js +149 -0
  166. package/dist/semantic-cache.js.map +1 -0
  167. package/dist/semantic.d.ts +78 -0
  168. package/dist/semantic.js +237 -0
  169. package/dist/semantic.js.map +1 -0
  170. package/dist/sensitive-data.d.ts +8 -0
  171. package/dist/sensitive-data.js +157 -0
  172. package/dist/sensitive-data.js.map +1 -0
  173. package/dist/signals.js +1 -1
  174. package/dist/signals.js.map +1 -1
  175. package/dist/supply-chain.d.ts +38 -0
  176. package/dist/supply-chain.js +206 -0
  177. package/dist/supply-chain.js.map +1 -0
  178. package/dist/test-reliability.d.ts +56 -0
  179. package/dist/test-reliability.js +191 -0
  180. package/dist/test-reliability.js.map +1 -0
  181. package/dist/text.js +8 -1
  182. package/dist/text.js.map +1 -1
  183. package/dist/transformers-embedding.d.ts +16 -0
  184. package/dist/transformers-embedding.js +127 -0
  185. package/dist/transformers-embedding.js.map +1 -0
  186. package/dist/types.d.ts +79 -2
  187. package/dist/validate.js +172 -0
  188. package/dist/validate.js.map +1 -1
  189. package/dist/verify.js +136 -2
  190. package/dist/verify.js.map +1 -1
  191. package/dist/workspace.d.ts +86 -0
  192. package/dist/workspace.js +557 -0
  193. package/dist/workspace.js.map +1 -0
  194. package/package.json +2 -2
@@ -0,0 +1,200 @@
1
+ import { annotationsForPath } from "./annotations.js";
2
+ import { buildChangeScope } from "./change-scope.js";
3
+ import { validateFixMapReport } from "./validate.js";
4
+ const REQUEST_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
5
+ const METHODS = ["fixmap/capabilities", "fixmap/plan", "fixmap/file", "fixmap/annotations"];
6
+ /** Creates one immutable, versioned view shared by editor adapters and the CLI report contract. */
7
+ export function createEditorProtocolSnapshot(candidate, repository) {
8
+ const validated = validateFixMapReport(candidate, "editor protocol report");
9
+ if (!validated.success)
10
+ throw new Error(validated.message);
11
+ if (validated.report.reportVersion !== 1) {
12
+ throw new Error("Editor protocol requires an explicit reportVersion 1 report.");
13
+ }
14
+ const report = structuredClone(validated.report);
15
+ const repo = repository ? structuredClone(repository) : undefined;
16
+ return deepFreeze({
17
+ editorProtocolVersion: 1,
18
+ sourceReportVersion: 1,
19
+ snapshotFingerprint: snapshotIdentity(report, repo),
20
+ privacy: { transport: "local-process", networkRequired: false, sourceUpload: false, mutationSupported: false },
21
+ methods: repo ? [...METHODS, "fixmap/change-scope"] : [...METHODS],
22
+ report,
23
+ ...(repo ? { repository: repo } : {})
24
+ });
25
+ }
26
+ export function handleEditorProtocolRequest(snapshot, candidate) {
27
+ validateSnapshot(snapshot);
28
+ const envelope = validateRequest(candidate);
29
+ if ("error" in envelope)
30
+ return response(snapshot, envelope.id, { error: envelope.error });
31
+ const request = envelope.request;
32
+ if (request.method === "fixmap/change-scope") {
33
+ if (!snapshot.repository)
34
+ return response(snapshot, request.id, { error: { code: "method-not-found", message: "Change scope requires a repository-backed snapshot; a saved plan is insufficient." } });
35
+ const params = request.params;
36
+ if (!params || !validChangeScopeParams(params)) {
37
+ return invalidParams(snapshot, request.id, "Change scope requires explicit anchors, identities, assessment time, and optional traversal bounds.");
38
+ }
39
+ try {
40
+ return response(snapshot, request.id, { result: buildChangeScope(snapshot.repository, params) });
41
+ }
42
+ catch (error) {
43
+ return invalidParams(snapshot, request.id, error instanceof Error ? error.message : "Invalid change scope parameters.");
44
+ }
45
+ }
46
+ if (request.method === "fixmap/capabilities") {
47
+ if (!emptyParams(request.params))
48
+ return invalidParams(snapshot, request.id, "fixmap/capabilities accepts no parameters.");
49
+ return response(snapshot, request.id, { result: {
50
+ methods: snapshot.methods,
51
+ privacy: snapshot.privacy,
52
+ sourceReportVersion: snapshot.sourceReportVersion
53
+ } });
54
+ }
55
+ if (request.method === "fixmap/plan") {
56
+ if (!emptyParams(request.params))
57
+ return invalidParams(snapshot, request.id, "fixmap/plan accepts no parameters.");
58
+ const report = snapshot.report;
59
+ return response(snapshot, request.id, { result: {
60
+ summary: report.summary,
61
+ contextFiles: report.contextFiles,
62
+ changedFiles: report.changedFiles,
63
+ impact: report.impact ?? null,
64
+ testRoutes: report.testRoutes,
65
+ risks: report.risks,
66
+ diagnostics: report.diagnostics,
67
+ analysis: report.analysis ?? null,
68
+ retrieval: report.retrieval ?? null,
69
+ policy: report.policy ?? null
70
+ } });
71
+ }
72
+ if (request.method === "fixmap/file") {
73
+ const path = requestPath(request.params);
74
+ if (!path)
75
+ return invalidParams(snapshot, request.id, "fixmap/file requires one safe repository-relative path.");
76
+ const report = snapshot.report;
77
+ return response(snapshot, request.id, { result: {
78
+ path,
79
+ context: report.contextFiles.find((file) => file.path === path) ?? null,
80
+ impact: report.impact?.files.find((file) => file.path === path) ?? null,
81
+ impactSeed: report.impact?.seeds.includes(path) ?? false,
82
+ testRoutes: report.testRoutes.filter((route) => route.relatedFiles.includes(path)),
83
+ annotations: report.annotations ? annotationsForPath(report.annotations.entries, path) : [],
84
+ decisions: (report.decisions ?? []).filter((decision) => decision.path === path || decision.targets.some((target) => (target.kind === "file" && target.path === path) || (target.kind === "symbol" && target.path === path))),
85
+ policyFindings: report.policy?.findings.filter((finding) => finding.paths.includes(path)) ?? [],
86
+ repositoryRisks: report.risks
87
+ } });
88
+ }
89
+ if (request.method === "fixmap/annotations") {
90
+ const params = request.params ?? {};
91
+ if (!isRecord(params) || Object.keys(params).some((key) => key !== "path")) {
92
+ return invalidParams(snapshot, request.id, "fixmap/annotations accepts only an optional safe repository-relative path.");
93
+ }
94
+ const path = params.path === undefined ? undefined : requestPath(params);
95
+ if (params.path !== undefined && !path) {
96
+ return invalidParams(snapshot, request.id, "fixmap/annotations path must be repository-relative.");
97
+ }
98
+ const annotations = snapshot.report.annotations;
99
+ return response(snapshot, request.id, { result: {
100
+ source: annotations ? { path: annotations.sourcePath, fingerprint: annotations.sourceFingerprint, asOf: annotations.asOf } : null,
101
+ entries: annotations ? (path ? annotationsForPath(annotations.entries, path) : annotations.entries) : [],
102
+ mutationSupported: false
103
+ } });
104
+ }
105
+ return response(snapshot, request.id, { error: { code: "method-not-found", message: `Unsupported editor protocol method: ${String(request.method)}` } });
106
+ }
107
+ function validateSnapshot(snapshot) {
108
+ if (!snapshot || snapshot.editorProtocolVersion !== 1 || snapshot.sourceReportVersion !== 1 ||
109
+ snapshot.report?.reportVersion !== 1 || snapshot.snapshotFingerprint !== snapshotIdentity(snapshot.report, snapshot.repository) ||
110
+ snapshot.privacy?.transport !== "local-process" || snapshot.privacy.networkRequired !== false ||
111
+ snapshot.privacy.sourceUpload !== false || snapshot.privacy.mutationSupported !== false) {
112
+ throw new Error("Invalid or mutated editor protocol snapshot.");
113
+ }
114
+ }
115
+ function validateRequest(candidate) {
116
+ const id = isRecord(candidate) && typeof candidate.id === "string" && REQUEST_ID.test(candidate.id) ? candidate.id : null;
117
+ if (!isRecord(candidate))
118
+ return { id, error: { code: "invalid-request", message: "Editor protocol request must be an object." } };
119
+ if (candidate.editorProtocolVersion !== 1) {
120
+ return { id, error: { code: "unsupported-version", message: "This FixMap build supports editorProtocolVersion 1." } };
121
+ }
122
+ if (!id || typeof candidate.method !== "string") {
123
+ return { id, error: { code: "invalid-request", message: "Editor protocol request needs a valid id and method." } };
124
+ }
125
+ if (!METHODS.includes(candidate.method) && candidate.method !== "fixmap/change-scope") {
126
+ return { id, error: { code: "method-not-found", message: `Unsupported editor protocol method: ${candidate.method}` } };
127
+ }
128
+ if (candidate.params !== undefined && !isRecord(candidate.params)) {
129
+ return { id, error: { code: "invalid-params", message: "Editor protocol params must be an object." } };
130
+ }
131
+ return { request: {
132
+ editorProtocolVersion: 1, id, method: candidate.method,
133
+ ...(candidate.params ? { params: candidate.params } : {})
134
+ } };
135
+ }
136
+ function response(snapshot, id, body) {
137
+ return { editorProtocolVersion: 1, id, snapshotFingerprint: snapshot.snapshotFingerprint, ...body };
138
+ }
139
+ function invalidParams(snapshot, id, message) {
140
+ return response(snapshot, id, { error: { code: "invalid-params", message } });
141
+ }
142
+ function emptyParams(value) { return value === undefined || Object.keys(value).length === 0; }
143
+ function validChangeScopeParams(params) {
144
+ if (Object.keys(params).some((key) => !["workspace", "repository", "anchors", "direction", "maxDepth", "maxNodes", "asOf"].includes(key)))
145
+ return false;
146
+ if (typeof params.workspace !== "string" || typeof params.repository !== "string" || typeof params.asOf !== "string")
147
+ return false;
148
+ if (!Array.isArray(params.anchors) || params.anchors.length < 1 || params.anchors.length > 64)
149
+ return false;
150
+ if (!params.anchors.every((anchor) => isRecord(anchor) &&
151
+ Object.keys(anchor).every((key) => key === "operation" || key === "path") &&
152
+ (anchor.operation === "touch" || anchor.operation === "add") && typeof anchor.path === "string" && safePath(anchor.path)))
153
+ return false;
154
+ if (params.direction !== undefined && (typeof params.direction !== "string" || !["dependencies", "dependents", "both"].includes(params.direction)))
155
+ return false;
156
+ return ["maxDepth", "maxNodes"].every((key) => params[key] === undefined || (typeof params[key] === "number" && Number.isInteger(params[key])));
157
+ }
158
+ function requestPath(params) {
159
+ if (!params || Object.keys(params).some((key) => key !== "path") || typeof params.path !== "string" || !safePath(params.path))
160
+ return undefined;
161
+ return params.path.replace(/\\/g, "/");
162
+ }
163
+ function safePath(value) {
164
+ const normalized = value.replace(/\\/g, "/");
165
+ return Boolean(normalized) && normalized.length <= 1_000 && !normalized.includes("\0") && !/^(?:[\/]|[A-Za-z]:)/.test(value) &&
166
+ normalized.split("/").every((part) => part && part !== "." && part !== "..");
167
+ }
168
+ function isRecord(value) {
169
+ return typeof value === "object" && value !== null && !Array.isArray(value);
170
+ }
171
+ function deepFreeze(value) {
172
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
173
+ for (const nested of Object.values(value))
174
+ deepFreeze(nested);
175
+ Object.freeze(value);
176
+ }
177
+ return value;
178
+ }
179
+ function canonicalize(value) {
180
+ if (Array.isArray(value))
181
+ return `[${value.map(canonicalize).join(",")}]`;
182
+ if (value && typeof value === "object")
183
+ return `{${Object.entries(value)
184
+ .filter(([, entry]) => entry !== undefined).sort(([a], [b]) => a.localeCompare(b))
185
+ .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalize(entry)}`).join(",")}}`;
186
+ return JSON.stringify(value);
187
+ }
188
+ function snapshotIdentity(report, repository) {
189
+ return `editor-snapshot:${stableHash(canonicalize(repository ? { report, repository } : report))}`;
190
+ }
191
+ /** FNV-1a is a deterministic snapshot identity, not a security digest. */
192
+ function stableHash(value) {
193
+ let hash = 0xcbf29ce484222325n;
194
+ for (const byte of new TextEncoder().encode(value)) {
195
+ hash ^= BigInt(byte);
196
+ hash = BigInt.asUintN(64, hash * 0x100000001b3n);
197
+ }
198
+ return hash.toString(16).padStart(16, "0");
199
+ }
200
+ //# sourceMappingURL=editor-protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"editor-protocol.js","sourceRoot":"","sources":["../src/editor-protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtD,OAAO,EAAE,gBAAgB,EAAyB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AI,CAAC,CAAC;QACrB,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,EAAE,EAAE,IAAI,GAAG,cAAc,CAAC,CAAC;IACnD,CAAC;IACD,OAAO,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { type EditorProtocolSnapshot } from "./editor-protocol.js";
2
+ import type { RepoMap } from "./types.js";
3
+ export type EditorSnapshotInput = {
4
+ report: unknown;
5
+ repository?: RepoMap;
6
+ };
7
+ /** Host-owned refresh ordering. Loaders must return evidence from one coherent scan. */
8
+ export declare function createEditorSession(initial: EditorSnapshotInput): {
9
+ snapshot(): EditorProtocolSnapshot;
10
+ refresh(load: () => Promise<EditorSnapshotInput>): Promise<{
11
+ applied: boolean;
12
+ snapshotFingerprint: string;
13
+ }>;
14
+ close(): void;
15
+ };
@@ -0,0 +1,27 @@
1
+ import { createEditorProtocolSnapshot } from "./editor-protocol.js";
2
+ /** Host-owned refresh ordering. Loaders must return evidence from one coherent scan. */
3
+ export function createEditorSession(initial) {
4
+ let current = createEditorProtocolSnapshot(initial.report, initial.repository);
5
+ let generation = 0;
6
+ let closed = false;
7
+ return {
8
+ snapshot() {
9
+ if (closed)
10
+ throw new Error("Editor session is closed.");
11
+ return current;
12
+ },
13
+ async refresh(load) {
14
+ if (closed)
15
+ throw new Error("Editor session is closed.");
16
+ const requested = ++generation;
17
+ const input = await load();
18
+ if (closed || requested !== generation)
19
+ return { applied: false, snapshotFingerprint: current.snapshotFingerprint };
20
+ const replacement = createEditorProtocolSnapshot(input.report, input.repository);
21
+ current = replacement;
22
+ return { applied: true, snapshotFingerprint: current.snapshotFingerprint };
23
+ },
24
+ close() { closed = true; generation++; }
25
+ };
26
+ }
27
+ //# sourceMappingURL=editor-session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"editor-session.js","sourceRoot":"","sources":["../src/editor-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,4BAA4B,EAA+B,MAAM,sBAAsB,CAAC;AAKjG,wFAAwF;AACxF,MAAM,UAAU,mBAAmB,CAAC,OAA4B;IAC9D,IAAI,OAAO,GAAG,4BAA4B,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;IAC/E,IAAI,UAAU,GAAG,CAAC,CAAC;IACnB,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,OAAO;QACL,QAAQ;YACN,IAAI,MAAM;gBAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;YACzD,OAAO,OAAO,CAAC;QACjB,CAAC;QACD,KAAK,CAAC,OAAO,CAAC,IAAwC;YACpD,IAAI,MAAM;gBAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;YACzD,MAAM,SAAS,GAAG,EAAE,UAAU,CAAC;YAC/B,MAAM,KAAK,GAAG,MAAM,IAAI,EAAE,CAAC;YAC3B,IAAI,MAAM,IAAI,SAAS,KAAK,UAAU;gBAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,OAAO,CAAC,mBAAmB,EAAE,CAAC;YACpH,MAAM,WAAW,GAAG,4BAA4B,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;YACjF,OAAO,GAAG,WAAW,CAAC;YACtB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,mBAAmB,EAAE,OAAO,CAAC,mBAAmB,EAAE,CAAC;QAC7E,CAAC;QACD,KAAK,KAAW,MAAM,GAAG,IAAI,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;KAC/C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { type EditorProtocolSnapshot } from "./editor-protocol.js";
2
+ import { Readable, type Writable } from "node:stream";
3
+ export declare const EDITOR_REQUEST_MAX_BYTES = 65536;
4
+ export declare const EDITOR_RESPONSE_MAX_BYTES: number;
5
+ /** A synchronous host getter publishes only fully constructed immutable snapshots. */
6
+ export type EditorSnapshotSource = EditorProtocolSnapshot | (() => EditorProtocolSnapshot);
7
+ /** Owns these session streams: completion ends output; failure/abort destroys both. */
8
+ export declare function runEditorStreams(snapshot: EditorSnapshotSource, input: Readable, output: Writable, signal?: AbortSignal): Promise<void>;
9
+ /** Local NDJSON framing. The host owns streams/lifecycle; yielding supplies backpressure. */
10
+ export declare function serveEditorProtocol(source: EditorSnapshotSource, input: AsyncIterable<Uint8Array>): AsyncGenerator<string>;
@@ -0,0 +1,75 @@
1
+ import { handleEditorProtocolRequest } from "./editor-protocol.js";
2
+ import { Readable } from "node:stream";
3
+ import { pipeline } from "node:stream/promises";
4
+ export const EDITOR_REQUEST_MAX_BYTES = 65_536;
5
+ export const EDITOR_RESPONSE_MAX_BYTES = 4 * 1024 * 1024;
6
+ /** Owns these session streams: completion ends output; failure/abort destroys both. */
7
+ export async function runEditorStreams(snapshot, input, output, signal) {
8
+ // Keep stdin byte-oriented: string decoding would conceal malformed UTF-8.
9
+ if (input.readableEncoding !== null)
10
+ throw new Error("Editor input must be a byte stream without a text encoding.");
11
+ signal?.throwIfAborted();
12
+ const stopInput = () => { input.destroy(); };
13
+ signal?.addEventListener("abort", stopInput, { once: true });
14
+ output.once("error", stopInput);
15
+ output.once("close", stopInput);
16
+ try {
17
+ await pipeline(Readable.from(serveEditorProtocol(snapshot, input)), output, { signal });
18
+ }
19
+ finally {
20
+ signal?.removeEventListener("abort", stopInput);
21
+ output.removeListener("error", stopInput);
22
+ output.removeListener("close", stopInput);
23
+ input.destroy();
24
+ }
25
+ }
26
+ /** Local NDJSON framing. The host owns streams/lifecycle; yielding supplies backpressure. */
27
+ export async function* serveEditorProtocol(source, input) {
28
+ const frame = new Uint8Array(EDITOR_REQUEST_MAX_BYTES);
29
+ let length = 0;
30
+ let oversized = false;
31
+ const render = () => {
32
+ const snapshot = typeof source === "function" ? source() : source;
33
+ const failure = (message) => ({
34
+ editorProtocolVersion: 1, id: null, snapshotFingerprint: snapshot.snapshotFingerprint,
35
+ error: { code: "invalid-request", message }
36
+ });
37
+ let result;
38
+ if (oversized)
39
+ result = failure("Editor request exceeds 64 KiB.");
40
+ else {
41
+ let request;
42
+ try {
43
+ request = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(frame.subarray(0, length)));
44
+ }
45
+ catch {
46
+ return `${JSON.stringify(failure("Editor request must be valid UTF-8 JSON."))}\n`;
47
+ }
48
+ result = handleEditorProtocolRequest(snapshot, request);
49
+ }
50
+ const output = JSON.stringify(result);
51
+ if (Buffer.byteLength(output, "utf8") > EDITOR_RESPONSE_MAX_BYTES) {
52
+ return `${JSON.stringify({ ...failure("Editor response exceeds 4 MiB; request a narrower view."), id: result.id })}\n`;
53
+ }
54
+ return `${output}\n`;
55
+ };
56
+ for await (const chunk of input) {
57
+ for (const byte of chunk) {
58
+ if (byte === 10) {
59
+ if (length > 0 || oversized)
60
+ yield render();
61
+ length = 0;
62
+ oversized = false;
63
+ }
64
+ else if (!oversized) {
65
+ if (length === frame.length)
66
+ oversized = true;
67
+ else
68
+ frame[length++] = byte;
69
+ }
70
+ }
71
+ }
72
+ if (length > 0 || oversized)
73
+ yield render();
74
+ }
75
+ //# sourceMappingURL=editor-transport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"editor-transport.js","sourceRoot":"","sources":["../src/editor-transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAA4D,MAAM,sBAAsB,CAAC;AAC7H,OAAO,EAAE,QAAQ,EAAiB,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAEhD,MAAM,CAAC,MAAM,wBAAwB,GAAG,MAAM,CAAC;AAC/C,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAIzD,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gBAAgB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AAI,KAAK,EAAE,MAAM,KAAK,IAAI,KAAK,EAAE,CAAC;QAChC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,IAAI,KAAK,EAAE,EAAE,CAAC;gBAChB,IAAI,MAAM,GAAG,CAAC,IAAI,SAAS;oBAAE,MAAM,MAAM,EAAE,CAAC;gBAC5C,MAAM,GAAG,CAAC,CAAC;gBACX,SAAS,GAAG,KAAK,CAAC;YACpB,CAAC;iBAAM,IAAI,CAAC,SAAS,EAAE,CAAC;gBACtB,IAAI,MAAM,KAAK,KAAK,CAAC,MAAM;oBAAE,SAAS,GAAG,IAAI,CAAC;;oBACzC,KAAK,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC;YAC9B,CAAC;QACH,CAAC;IACH,CAAC;IACD,IAAI,MAAM,GAAG,CAAC,IAAI,SAAS;QAAE,MAAM,MAAM,EAAE,CAAC;AAC9C,CAAC"}
@@ -0,0 +1,82 @@
1
+ export type EnterpriseAction = "read" | "create" | "update" | "delete" | "execute" | "admin";
2
+ export type EnterpriseResourceKind = "repository" | "report" | "annotation" | "dossier" | "runtime-evidence" | "configuration";
3
+ export type EnterprisePolicy = {
4
+ enterprisePolicyVersion: 1;
5
+ tenantId: string;
6
+ sourceFingerprint: string;
7
+ roles: Array<{
8
+ role: string;
9
+ grants: Array<{
10
+ resource: EnterpriseResourceKind;
11
+ actions: EnterpriseAction[];
12
+ }>;
13
+ }>;
14
+ retentionDays: Partial<Record<EnterpriseResourceKind | "audit-event", number>>;
15
+ };
16
+ export type EnterpriseAuthorizationRequest = {
17
+ requestId: string;
18
+ requestedAt: string;
19
+ actor: {
20
+ subjectId: string;
21
+ tenantId: string;
22
+ roles: string[];
23
+ };
24
+ authentication: {
25
+ issuer: string;
26
+ audience: string;
27
+ credentialFingerprint: string;
28
+ authenticatedAt: string;
29
+ expiresAt: string;
30
+ };
31
+ action: EnterpriseAction;
32
+ resource: {
33
+ tenantId: string;
34
+ kind: EnterpriseResourceKind;
35
+ id: string;
36
+ };
37
+ };
38
+ export type EnterpriseAuthorizationDecision = {
39
+ enterpriseAuthorizationVersion: 1;
40
+ request: EnterpriseAuthorizationRequest;
41
+ policyFingerprint: string;
42
+ allowed: boolean;
43
+ reason: "allowed-by-role" | "tenant-boundary" | "policy-tenant-mismatch" | "authentication-expired" | "authentication-not-yet-valid" | "role-not-granted";
44
+ matchedRoles: string[];
45
+ authenticationVerifiedByFixMap: false;
46
+ };
47
+ export type EnterpriseAuditEvent = {
48
+ enterpriseAuditVersion: 1;
49
+ eventFingerprint: string;
50
+ previousEventFingerprint: string | null;
51
+ occurredAt: string;
52
+ decision: EnterpriseAuthorizationDecision;
53
+ outcome: "succeeded" | "failed" | "denied";
54
+ outcomeReference?: string;
55
+ };
56
+ /** Authorization consumes a caller-verified authentication attestation; FixMap never claims to validate the credential itself. */
57
+ export declare function authorizeEnterpriseAction(policyInput: EnterprisePolicy, requestInput: EnterpriseAuthorizationRequest): EnterpriseAuthorizationDecision;
58
+ export declare function createEnterpriseAuditEvent(input: {
59
+ decision: EnterpriseAuthorizationDecision;
60
+ occurredAt: string;
61
+ outcome: EnterpriseAuditEvent["outcome"];
62
+ outcomeReference?: string;
63
+ previousEventFingerprint?: string;
64
+ }): Promise<EnterpriseAuditEvent>;
65
+ export declare function verifyEnterpriseAuditChain(events: readonly EnterpriseAuditEvent[]): Promise<{
66
+ valid: boolean;
67
+ invalidIndex: number | null;
68
+ message: string;
69
+ }>;
70
+ export declare function assessEnterpriseRetention(policyInput: EnterprisePolicy, input: {
71
+ tenantId: string;
72
+ kind: EnterpriseResourceKind | "audit-event";
73
+ createdAt: string;
74
+ asOf: string;
75
+ legalHold: boolean;
76
+ }): {
77
+ decision: "retain" | "deletion-eligible";
78
+ reason: "legal-hold" | "retention-not-configured" | "inside-retention-window" | "retention-window-expired";
79
+ expiresAt: string | null;
80
+ automaticDeletion: false;
81
+ };
82
+ export declare function validateEnterprisePolicy(policy: EnterprisePolicy): EnterprisePolicy;
@@ -0,0 +1,170 @@
1
+ const ID = /^[A-Za-z0-9][A-Za-z0-9._:/@-]{0,499}$/;
2
+ const FINGERPRINT = /^[A-Za-z][A-Za-z0-9._-]*:[A-Za-z0-9._-]{4,255}$/;
3
+ const ACTIONS = ["read", "create", "update", "delete", "execute", "admin"];
4
+ const RESOURCES = ["repository", "report", "annotation", "dossier", "runtime-evidence", "configuration"];
5
+ /** Authorization consumes a caller-verified authentication attestation; FixMap never claims to validate the credential itself. */
6
+ export function authorizeEnterpriseAction(policyInput, requestInput) {
7
+ const policy = validateEnterprisePolicy(policyInput);
8
+ const request = validateAuthorizationRequest(requestInput);
9
+ let reason = "role-not-granted";
10
+ let allowed = false;
11
+ const matchedRoles = [];
12
+ if (policy.tenantId !== request.actor.tenantId)
13
+ reason = "policy-tenant-mismatch";
14
+ else if (request.actor.tenantId !== request.resource.tenantId)
15
+ reason = "tenant-boundary";
16
+ else if (Date.parse(request.requestedAt) >= Date.parse(request.authentication.expiresAt))
17
+ reason = "authentication-expired";
18
+ else if (Date.parse(request.requestedAt) < Date.parse(request.authentication.authenticatedAt))
19
+ reason = "authentication-not-yet-valid";
20
+ else {
21
+ for (const roleName of request.actor.roles) {
22
+ const role = policy.roles.find((entry) => entry.role === roleName);
23
+ if (role?.grants.some((grant) => grant.resource === request.resource.kind && grant.actions.includes(request.action)))
24
+ matchedRoles.push(roleName);
25
+ }
26
+ allowed = matchedRoles.length > 0;
27
+ reason = allowed ? "allowed-by-role" : "role-not-granted";
28
+ }
29
+ return {
30
+ enterpriseAuthorizationVersion: 1,
31
+ request,
32
+ policyFingerprint: policy.sourceFingerprint,
33
+ allowed,
34
+ reason,
35
+ matchedRoles: [...new Set(matchedRoles)].sort(),
36
+ authenticationVerifiedByFixMap: false
37
+ };
38
+ }
39
+ export async function createEnterpriseAuditEvent(input) {
40
+ if (!validAuthorizationDecision(input.decision) || !validDate(input.occurredAt) ||
41
+ !["succeeded", "failed", "denied"].includes(input.outcome) ||
42
+ (input.decision.allowed === false && input.outcome !== "denied") || (input.decision.allowed === true && input.outcome === "denied") ||
43
+ Date.parse(input.occurredAt) < Date.parse(input.decision.request.requestedAt) ||
44
+ (input.outcomeReference !== undefined && !bounded(input.outcomeReference, 1_000)) ||
45
+ (input.previousEventFingerprint !== undefined && !/^audit:sha256:[a-f0-9]{64}$/.test(input.previousEventFingerprint))) {
46
+ throw new Error("Invalid enterprise audit event input.");
47
+ }
48
+ const content = {
49
+ enterpriseAuditVersion: 1,
50
+ previousEventFingerprint: input.previousEventFingerprint ?? null,
51
+ occurredAt: new Date(input.occurredAt).toISOString(),
52
+ decision: structuredClone(input.decision),
53
+ outcome: input.outcome,
54
+ ...(input.outcomeReference ? { outcomeReference: input.outcomeReference.trim() } : {})
55
+ };
56
+ return { ...content, eventFingerprint: `audit:sha256:${await sha256(canonicalize(content))}` };
57
+ }
58
+ function validAuthorizationDecision(decision) {
59
+ if (!decision || decision.enterpriseAuthorizationVersion !== 1 || !fingerprint(decision.policyFingerprint) ||
60
+ decision.authenticationVerifiedByFixMap !== false || !Array.isArray(decision.matchedRoles))
61
+ return false;
62
+ try {
63
+ const request = validateAuthorizationRequest(decision.request);
64
+ if (canonicalize(request) !== canonicalize(decision.request))
65
+ return false;
66
+ }
67
+ catch {
68
+ return false;
69
+ }
70
+ if (decision.allowed)
71
+ return decision.reason === "allowed-by-role" && decision.matchedRoles.length > 0;
72
+ return decision.reason !== "allowed-by-role" && decision.matchedRoles.length === 0;
73
+ }
74
+ export async function verifyEnterpriseAuditChain(events) {
75
+ if (!Array.isArray(events) || events.length > 1_000_000)
76
+ return { valid: false, invalidIndex: null, message: "Invalid audit chain envelope." };
77
+ let previous = null;
78
+ let previousOccurredAt = -Infinity;
79
+ for (let index = 0; index < events.length; index += 1) {
80
+ const event = events[index];
81
+ if (!event || event.enterpriseAuditVersion !== 1 || event.previousEventFingerprint !== previous) {
82
+ return { valid: false, invalidIndex: index, message: "Audit chain link does not match the preceding event." };
83
+ }
84
+ if (!validDate(event.occurredAt) || Date.parse(event.occurredAt) < previousOccurredAt) {
85
+ return { valid: false, invalidIndex: index, message: "Audit event time precedes the previous event." };
86
+ }
87
+ const { eventFingerprint, ...content } = event;
88
+ if (eventFingerprint !== `audit:sha256:${await sha256(canonicalize(content))}`) {
89
+ return { valid: false, invalidIndex: index, message: "Audit event fingerprint does not match its content." };
90
+ }
91
+ previous = eventFingerprint;
92
+ previousOccurredAt = Date.parse(event.occurredAt);
93
+ }
94
+ return { valid: true, invalidIndex: null, message: `${events.length} audit event${events.length === 1 ? "" : "s"} form a valid ordered hash chain.` };
95
+ }
96
+ export function assessEnterpriseRetention(policyInput, input) {
97
+ const policy = validateEnterprisePolicy(policyInput);
98
+ if (!input || input.tenantId !== policy.tenantId || ![...RESOURCES, "audit-event"].includes(input.kind) ||
99
+ !validDate(input.createdAt) || !validDate(input.asOf) || Date.parse(input.asOf) < Date.parse(input.createdAt) || typeof input.legalHold !== "boolean") {
100
+ throw new Error("Invalid enterprise retention assessment.");
101
+ }
102
+ const days = policy.retentionDays[input.kind];
103
+ if (input.legalHold)
104
+ return { decision: "retain", reason: "legal-hold", expiresAt: null, automaticDeletion: false };
105
+ if (days === undefined)
106
+ return { decision: "retain", reason: "retention-not-configured", expiresAt: null, automaticDeletion: false };
107
+ const expiresAt = new Date(Date.parse(input.createdAt) + days * 86_400_000).toISOString();
108
+ return Date.parse(input.asOf) >= Date.parse(expiresAt)
109
+ ? { decision: "deletion-eligible", reason: "retention-window-expired", expiresAt, automaticDeletion: false }
110
+ : { decision: "retain", reason: "inside-retention-window", expiresAt, automaticDeletion: false };
111
+ }
112
+ export function validateEnterprisePolicy(policy) {
113
+ if (!policy || policy.enterprisePolicyVersion !== 1 || !ID.test(policy.tenantId) || !fingerprint(policy.sourceFingerprint) ||
114
+ !Array.isArray(policy.roles) || policy.roles.length > 1_000 || !isRecord(policy.retentionDays) ||
115
+ Object.keys(policy.retentionDays).some((kind) => ![...RESOURCES, "audit-event"].includes(kind))) {
116
+ throw new Error("Invalid enterprise policy envelope.");
117
+ }
118
+ const roles = policy.roles.map((role, index) => {
119
+ if (!role || !ID.test(role.role) || !Array.isArray(role.grants) || role.grants.length > 1_000)
120
+ throw new Error(`Invalid enterprise role at index ${index}.`);
121
+ const grants = role.grants.map((grant, grantIndex) => {
122
+ if (!grant || !RESOURCES.includes(grant.resource) || !Array.isArray(grant.actions) || grant.actions.length === 0 ||
123
+ !grant.actions.every((action) => ACTIONS.includes(action)))
124
+ throw new Error(`Invalid enterprise grant at role ${role.role}, index ${grantIndex}.`);
125
+ return { resource: grant.resource, actions: [...new Set(grant.actions)].sort() };
126
+ }).sort((a, b) => a.resource.localeCompare(b.resource));
127
+ return { role: role.role, grants };
128
+ }).sort((a, b) => a.role.localeCompare(b.role));
129
+ assertUnique(roles.map((role) => role.role), "enterprise role");
130
+ const retentionDays = {};
131
+ for (const [kind, days] of Object.entries(policy.retentionDays)) {
132
+ if (!Number.isInteger(days) || Number(days) < 1 || Number(days) > 3_650)
133
+ throw new Error(`Invalid retention period for ${kind}.`);
134
+ retentionDays[kind] = Number(days);
135
+ }
136
+ return { enterprisePolicyVersion: 1, tenantId: policy.tenantId, sourceFingerprint: policy.sourceFingerprint, roles, retentionDays };
137
+ }
138
+ function validateAuthorizationRequest(request) {
139
+ if (!request || !ID.test(request.requestId) || !validDate(request.requestedAt) || !request.actor || !ID.test(request.actor.subjectId) ||
140
+ !ID.test(request.actor.tenantId) || !Array.isArray(request.actor.roles) || request.actor.roles.length > 100 || !request.actor.roles.every((role) => ID.test(role)) ||
141
+ !request.authentication || !bounded(request.authentication.issuer, 500) || !bounded(request.authentication.audience, 500) ||
142
+ !fingerprint(request.authentication.credentialFingerprint) || !validDate(request.authentication.authenticatedAt) ||
143
+ !validDate(request.authentication.expiresAt) || Date.parse(request.authentication.expiresAt) <= Date.parse(request.authentication.authenticatedAt) ||
144
+ !ACTIONS.includes(request.action) || !request.resource || !ID.test(request.resource.tenantId) ||
145
+ !RESOURCES.includes(request.resource.kind) || !ID.test(request.resource.id))
146
+ throw new Error("Invalid enterprise authorization request.");
147
+ return structuredClone({ ...request, requestedAt: new Date(request.requestedAt).toISOString(), actor: {
148
+ ...request.actor, roles: [...new Set(request.actor.roles)].sort()
149
+ }, authentication: { ...request.authentication, authenticatedAt: new Date(request.authentication.authenticatedAt).toISOString(),
150
+ expiresAt: new Date(request.authentication.expiresAt).toISOString() } });
151
+ }
152
+ function validDate(value) { return typeof value === "string" && Number.isFinite(Date.parse(value)); }
153
+ function bounded(value, max) { return typeof value === "string" && value.trim().length > 0 && value.length <= max && !value.includes("\0"); }
154
+ function fingerprint(value) { return typeof value === "string" && FINGERPRINT.test(value); }
155
+ function assertUnique(values, label) { const duplicate = values.find((value, index) => values.indexOf(value) !== index); if (duplicate)
156
+ throw new Error(`Duplicate ${label} id: ${duplicate}`); }
157
+ function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }
158
+ function canonicalize(value) {
159
+ if (Array.isArray(value))
160
+ return `[${value.map(canonicalize).join(",")}]`;
161
+ if (value && typeof value === "object")
162
+ return `{${Object.entries(value).filter(([, entry]) => entry !== undefined)
163
+ .sort(([a], [b]) => a.localeCompare(b)).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalize(entry)}`).join(",")}}`;
164
+ return JSON.stringify(value);
165
+ }
166
+ async function sha256(value) {
167
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
168
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
169
+ }
170
+ //# sourceMappingURL=enterprise-policy.js.map