@hve-squad/mcp 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +46 -0
  3. package/README.md +233 -0
  4. package/dist/src/auth/entra.js +164 -0
  5. package/dist/src/auth/jose-verifier.js +31 -0
  6. package/dist/src/auth/scopes.js +240 -0
  7. package/dist/src/catalog/catalog.js +80 -0
  8. package/dist/src/config/operator-config.js +281 -0
  9. package/dist/src/engine/advisory-pipeline.js +367 -0
  10. package/dist/src/engine/advisory-run-store.js +31 -0
  11. package/dist/src/engine/artifact-store.js +165 -0
  12. package/dist/src/engine/auto-memory.js +207 -0
  13. package/dist/src/engine/backends/azure-blob-artifact-store.js +246 -0
  14. package/dist/src/engine/backends/azure-openai.js +69 -0
  15. package/dist/src/engine/backends/azure-table-run-state.js +319 -0
  16. package/dist/src/engine/backends/azure-table-squad-memory.js +240 -0
  17. package/dist/src/engine/backends/file-squad-memory.js +208 -0
  18. package/dist/src/engine/backends/graph-squad-memory.js +271 -0
  19. package/dist/src/engine/backends/managed-identity-credential.js +33 -0
  20. package/dist/src/engine/backends/overflow-squad-memory.js +151 -0
  21. package/dist/src/engine/backlog-contract.js +200 -0
  22. package/dist/src/engine/business-tools.js +118 -0
  23. package/dist/src/engine/consumption.js +134 -0
  24. package/dist/src/engine/coordinator-engine.js +1 -0
  25. package/dist/src/engine/council.js +204 -0
  26. package/dist/src/engine/delegated.js +190 -0
  27. package/dist/src/engine/dispatch-loop.js +84 -0
  28. package/dist/src/engine/durable-run-state.js +251 -0
  29. package/dist/src/engine/embedded-prompt.js +35 -0
  30. package/dist/src/engine/embedded-roles.js +133 -0
  31. package/dist/src/engine/embedded.js +1023 -0
  32. package/dist/src/engine/federation.js +96 -0
  33. package/dist/src/engine/field-cipher.js +84 -0
  34. package/dist/src/engine/gates.js +241 -0
  35. package/dist/src/engine/markdown-table.js +43 -0
  36. package/dist/src/engine/model-backend.js +16 -0
  37. package/dist/src/engine/persona-loader.js +132 -0
  38. package/dist/src/engine/persona.js +287 -0
  39. package/dist/src/engine/profiles.js +237 -0
  40. package/dist/src/engine/render/pptx-render-service.js +60 -0
  41. package/dist/src/engine/render/python-pptx-render-backend.js +117 -0
  42. package/dist/src/engine/render/render-backend.js +25 -0
  43. package/dist/src/engine/render-embedded.js +69 -0
  44. package/dist/src/engine/routing.js +275 -0
  45. package/dist/src/engine/run-params.js +70 -0
  46. package/dist/src/engine/run-state.js +132 -0
  47. package/dist/src/engine/run-worker.js +60 -0
  48. package/dist/src/engine/squad-history.js +136 -0
  49. package/dist/src/engine/squad-ledger.js +215 -0
  50. package/dist/src/engine/squad-memory-resources.js +218 -0
  51. package/dist/src/engine/squad-memory-state.js +57 -0
  52. package/dist/src/engine/squad-run-recorder.js +212 -0
  53. package/dist/src/engine/targeted-squad-memory.js +94 -0
  54. package/dist/src/engine/workspace.js +68 -0
  55. package/dist/src/observability/logger.js +75 -0
  56. package/dist/src/observability/redact.js +77 -0
  57. package/dist/src/paths.js +108 -0
  58. package/dist/src/router/router.js +88 -0
  59. package/dist/src/server-http.js +304 -0
  60. package/dist/src/server.js +237 -0
  61. package/dist/src/transports/http-core.js +1240 -0
  62. package/dist/src/transports/http.js +90 -0
  63. package/dist/src/transports/session-store.js +78 -0
  64. package/dist/src/transports/stdio.js +12 -0
  65. package/dist/src/worker-main.js +87 -0
  66. package/generated/copilot-studio-connector/README.md +44 -0
  67. package/generated/copilot-studio-connector/agent-instructions.md +90 -0
  68. package/generated/copilot-studio-connector/apiDefinition.swagger.json +60 -0
  69. package/generated/copilot-studio-connector/apiProperties.json +35 -0
  70. package/generated/copilot-studio-connector/connector.manifest.json +86 -0
  71. package/generated/mcp-tools.schema.json +462 -0
  72. package/package.json +61 -0
  73. package/tools.catalog.yml +397 -0
@@ -0,0 +1,319 @@
1
+ /**
2
+ * Azure Table Storage run-state store (WI-06 — the multi-replica backbone).
3
+ *
4
+ * The file-backed {@link import("../durable-run-state.js").DurableRunStateStore}
5
+ * survives restarts but is single-replica: its `claim` is atomic only within one
6
+ * process, so two Container App replicas could both drive the same approved run.
7
+ * Azure Table Storage gives a shared, cross-replica store whose optimistic
8
+ * concurrency (ETag `If-Match`) is a true compare-and-swap: a claim PUT with a
9
+ * stale ETag fails 412, so EXACTLY ONE replica wins a held->running transition.
10
+ *
11
+ * Consistent with the house style (`backends/azure-openai.ts`), this talks to the
12
+ * Table REST API with `fetch` and an INJECTED managed-identity token provider, so
13
+ * there is NO Azure SDK dependency and the build/tests stay SDK-free. It is
14
+ * live-only: wired by `server-http.ts` / `worker-main.ts`, never imported by a
15
+ * test. Security posture:
16
+ *
17
+ * * SEC-3 — the storage account + table come from operator config, never a
18
+ * caller; a caller cannot redirect persistence elsewhere.
19
+ * * SEC-10 — the access token is registered with the logger for redaction and
20
+ * never logged; error paths never include the response body.
21
+ * * MEDIUM-3 — `request`/`context` are encrypted with the injected
22
+ * {@link FieldCipher} before they leave the process, so the caller's prompt
23
+ * text is opaque at rest even to an operator with raw table access.
24
+ *
25
+ * Partitioning: PartitionKey = tenantId (tenant partition; isolation is ALSO
26
+ * enforced in the engine by comparing `tenantId`), RowKey = runId (an unguessable
27
+ * CSPRNG UUID). `get(runId)` — which has no tenant in hand — resolves via a
28
+ * bounded cross-partition RowKey query (a run id is globally unique).
29
+ */
30
+ import { DEFAULT_LEASE_MS, isRunClaimable, isRunExpired, } from "../run-state.js";
31
+ import { isValidRunId } from "../durable-run-state.js";
32
+ import { NullFieldCipher, decryptField, encryptField } from "../field-cipher.js";
33
+ import { randomUUID } from "node:crypto";
34
+ /** The Table REST API version this client speaks. */
35
+ const TABLE_API_VERSION = "2019-02-02";
36
+ export class AzureTableRunStateStore {
37
+ kind = "durable";
38
+ account;
39
+ tableName;
40
+ getAccessToken;
41
+ cipher;
42
+ fetchImpl;
43
+ logger;
44
+ baseUrl;
45
+ /**
46
+ * WI-07 — memoized create-if-not-exists guard. Resolved once the table is known
47
+ * to exist (or was just created); a failure clears it so the next write retries
48
+ * rather than poisoning every subsequent write with a cached rejection.
49
+ */
50
+ tableEnsured;
51
+ constructor(options) {
52
+ this.account = options.account;
53
+ this.tableName = options.tableName;
54
+ this.getAccessToken = options.getAccessToken;
55
+ this.cipher = options.cipher ?? new NullFieldCipher();
56
+ this.fetchImpl = options.fetchImpl ?? fetch;
57
+ this.logger = options.logger;
58
+ const host = options.endpoint ?? `https://${this.account}.table.core.windows.net`;
59
+ this.baseUrl = host.replace(/\/$/, "");
60
+ }
61
+ async headers(extra = {}) {
62
+ const token = await this.getAccessToken();
63
+ this.logger?.registerSecret(token);
64
+ return {
65
+ Authorization: `Bearer ${token}`,
66
+ "x-ms-version": TABLE_API_VERSION,
67
+ "x-ms-date": new Date().toUTCString(),
68
+ Accept: "application/json;odata=nometadata",
69
+ "Content-Type": "application/json",
70
+ ...extra,
71
+ };
72
+ }
73
+ /**
74
+ * WI-07 — idempotently create the backing table before the first write. Issues
75
+ * `POST <baseUrl>/Tables` with `{"TableName": <tableName>}`; a 201/204 means it
76
+ * was created and a 409 means it already exists — both are success. The result
77
+ * is memoized so only the FIRST write pays the round-trip; a failure clears the
78
+ * memo so a later write can retry instead of inheriting a cached rejection.
79
+ */
80
+ ensureTable() {
81
+ if (this.tableEnsured === undefined) {
82
+ this.tableEnsured = this.createTable().catch((error) => {
83
+ this.tableEnsured = undefined;
84
+ throw error;
85
+ });
86
+ }
87
+ return this.tableEnsured;
88
+ }
89
+ async createTable() {
90
+ const response = await this.fetchImpl(`${this.baseUrl}/Tables`, {
91
+ method: "POST",
92
+ headers: await this.headers({ Prefer: "return-no-content" }),
93
+ body: JSON.stringify({ TableName: this.tableName }),
94
+ });
95
+ // 201/204 -> created; 409 -> already exists. Both mean the table is ready.
96
+ if (response.status === 201 || response.status === 204 || response.status === 409) {
97
+ return;
98
+ }
99
+ throw new Error(`Table create failed with status ${response.status}.`);
100
+ }
101
+ entityUrl(tenantId, runId) {
102
+ return `${this.baseUrl}/${this.tableName}(PartitionKey='${encodeURIComponent(tenantId)}',RowKey='${encodeURIComponent(runId)}')`;
103
+ }
104
+ /** Map a decrypted RunState to the sealed wire entity (request/context encrypted). */
105
+ toEntity(run) {
106
+ const entity = {
107
+ PartitionKey: run.tenantId,
108
+ RowKey: run.runId,
109
+ toolId: run.toolId,
110
+ status: run.status,
111
+ createdAt: run.createdAt,
112
+ };
113
+ if (run.updatedAt !== undefined)
114
+ entity.updatedAt = run.updatedAt;
115
+ if (run.holdReason !== undefined)
116
+ entity.holdReason = run.holdReason;
117
+ if (run.artifact !== undefined)
118
+ entity.artifact = run.artifact;
119
+ const sealedRequest = encryptField(this.cipher, run.request);
120
+ if (sealedRequest !== undefined)
121
+ entity.request = sealedRequest;
122
+ const sealedContext = encryptField(this.cipher, run.context);
123
+ if (sealedContext !== undefined)
124
+ entity.context = sealedContext;
125
+ const sealedParams = encryptField(this.cipher, run.params);
126
+ if (sealedParams !== undefined)
127
+ entity.params = sealedParams;
128
+ if (run.approvedBy !== undefined)
129
+ entity.approvedBy = run.approvedBy;
130
+ if (run.approvedAt !== undefined)
131
+ entity.approvedAt = run.approvedAt;
132
+ if (run.expiresAt !== undefined)
133
+ entity.expiresAt = run.expiresAt;
134
+ if (run.leaseExpiresAt !== undefined)
135
+ entity.leaseExpiresAt = run.leaseExpiresAt;
136
+ // Phase 4 — flatten + encrypt the advisory composites; history is plain metadata.
137
+ if (run.stages !== undefined) {
138
+ const sealedStages = encryptField(this.cipher, JSON.stringify(run.stages));
139
+ if (sealedStages !== undefined)
140
+ entity.stages = sealedStages;
141
+ }
142
+ if (run.councilVerdict !== undefined) {
143
+ const sealedVerdict = encryptField(this.cipher, JSON.stringify(run.councilVerdict));
144
+ if (sealedVerdict !== undefined)
145
+ entity.councilVerdict = sealedVerdict;
146
+ }
147
+ if (run.history !== undefined)
148
+ entity.history = JSON.stringify(run.history);
149
+ return entity;
150
+ }
151
+ /** Map a wire entity back to a decrypted RunState. */
152
+ fromEntity(entity) {
153
+ return {
154
+ runId: entity.RowKey,
155
+ tenantId: entity.PartitionKey,
156
+ toolId: entity.toolId,
157
+ status: entity.status,
158
+ createdAt: entity.createdAt,
159
+ updatedAt: entity.updatedAt,
160
+ holdReason: entity.holdReason,
161
+ artifact: entity.artifact,
162
+ request: decryptField(this.cipher, entity.request),
163
+ context: decryptField(this.cipher, entity.context),
164
+ params: decryptField(this.cipher, entity.params),
165
+ approvedBy: entity.approvedBy,
166
+ approvedAt: entity.approvedAt,
167
+ expiresAt: entity.expiresAt,
168
+ leaseExpiresAt: entity.leaseExpiresAt,
169
+ stages: entity.stages !== undefined
170
+ ? JSON.parse(decryptField(this.cipher, entity.stages))
171
+ : undefined,
172
+ councilVerdict: entity.councilVerdict !== undefined
173
+ ? JSON.parse(decryptField(this.cipher, entity.councilVerdict))
174
+ : undefined,
175
+ history: entity.history !== undefined ? JSON.parse(entity.history) : undefined,
176
+ };
177
+ }
178
+ /** Fetch the raw (still-sealed) entity + its ETag via a bounded RowKey query. */
179
+ async fetchEntity(runId) {
180
+ if (!isValidRunId(runId)) {
181
+ return undefined;
182
+ }
183
+ const url = `${this.baseUrl}/${this.tableName}()?$filter=${encodeURIComponent(`RowKey eq '${runId}'`)}&$top=1`;
184
+ const response = await this.fetchImpl(url, { method: "GET", headers: await this.headers() });
185
+ if (response.status === 404) {
186
+ return undefined;
187
+ }
188
+ if (!response.ok) {
189
+ throw new Error(`Table query failed with status ${response.status}.`);
190
+ }
191
+ const body = (await response.json());
192
+ return body.value?.[0];
193
+ }
194
+ async create(init) {
195
+ const now = Date.now();
196
+ const run = {
197
+ runId: randomUUID(),
198
+ tenantId: init.tenantId,
199
+ toolId: init.toolId,
200
+ status: "running",
201
+ createdAt: now,
202
+ updatedAt: now,
203
+ expiresAt: init.ttlMs !== undefined ? now + init.ttlMs : undefined,
204
+ };
205
+ // WI-07 — create the backing table on first write (memoized).
206
+ await this.ensureTable();
207
+ const response = await this.fetchImpl(`${this.baseUrl}/${this.tableName}`, {
208
+ method: "POST",
209
+ headers: await this.headers({ Prefer: "return-no-content" }),
210
+ body: JSON.stringify(this.toEntity(run)),
211
+ });
212
+ if (!response.ok) {
213
+ throw new Error(`Table insert failed with status ${response.status}.`);
214
+ }
215
+ return run;
216
+ }
217
+ async get(runId) {
218
+ const entity = await this.fetchEntity(runId);
219
+ if (!entity) {
220
+ return undefined;
221
+ }
222
+ const run = this.fromEntity(entity);
223
+ if (isRunExpired(run, Date.now())) {
224
+ await this.delete(runId);
225
+ return undefined;
226
+ }
227
+ return run;
228
+ }
229
+ /** Overwrite an entity guarding on its ETag (CAS); returns false on 412 conflict. */
230
+ async putWithEtag(run, etag) {
231
+ const response = await this.fetchImpl(this.entityUrl(run.tenantId, run.runId), {
232
+ method: "PUT",
233
+ headers: await this.headers({ "If-Match": etag ?? "*" }),
234
+ body: JSON.stringify(this.toEntity(run)),
235
+ });
236
+ if (response.status === 412) {
237
+ return false; // CAS lost — another replica won.
238
+ }
239
+ if (!response.ok) {
240
+ throw new Error(`Table update failed with status ${response.status}.`);
241
+ }
242
+ return true;
243
+ }
244
+ async update(runId, patch) {
245
+ const entity = await this.fetchEntity(runId);
246
+ if (!entity) {
247
+ return undefined;
248
+ }
249
+ const current = this.fromEntity(entity);
250
+ const next = { ...current, ...patch, updatedAt: Date.now() };
251
+ const ok = await this.putWithEtag(next, entity["odata.etag"]);
252
+ // A lost race on a plain update means a concurrent writer moved on; the caller
253
+ // treats undefined as "not applied" and re-reads if needed.
254
+ return ok ? next : undefined;
255
+ }
256
+ async delete(runId) {
257
+ const entity = await this.fetchEntity(runId);
258
+ if (!entity) {
259
+ return;
260
+ }
261
+ await this.fetchImpl(this.entityUrl(entity.PartitionKey, entity.RowKey), {
262
+ method: "DELETE",
263
+ headers: await this.headers({ "If-Match": "*" }),
264
+ });
265
+ }
266
+ async claim(runId, from, to, options = {}) {
267
+ const now = options.now ?? Date.now();
268
+ const entity = await this.fetchEntity(runId);
269
+ if (!entity) {
270
+ return undefined;
271
+ }
272
+ const current = this.fromEntity(entity);
273
+ if (isRunExpired(current, now) || !from.includes(current.status)) {
274
+ return undefined;
275
+ }
276
+ if (current.status === "running" && (current.leaseExpiresAt ?? 0) > now) {
277
+ return undefined;
278
+ }
279
+ const next = {
280
+ ...current,
281
+ status: to,
282
+ leaseExpiresAt: now + (options.leaseMs ?? DEFAULT_LEASE_MS),
283
+ updatedAt: now,
284
+ };
285
+ // ETag If-Match makes this a true CAS: a stale ETag (another replica claimed
286
+ // first) fails 412 and we return undefined — exactly one winner.
287
+ const won = await this.putWithEtag(next, entity["odata.etag"]);
288
+ return won ? next : undefined;
289
+ }
290
+ async listClaimable(now = Date.now()) {
291
+ // Query the candidate statuses cross-partition; decide claimability in-process
292
+ // (the OData filter cannot express the approved/lease predicate portably).
293
+ const filter = encodeURIComponent("status eq 'held' or status eq 'running'");
294
+ const url = `${this.baseUrl}/${this.tableName}()?$filter=${filter}`;
295
+ const response = await this.fetchImpl(url, { method: "GET", headers: await this.headers() });
296
+ if (!response.ok) {
297
+ throw new Error(`Table query failed with status ${response.status}.`);
298
+ }
299
+ const body = (await response.json());
300
+ return (body.value ?? [])
301
+ .map((entity) => this.fromEntity(entity))
302
+ .filter((run) => !isRunExpired(run, now) && isRunClaimable(run, now));
303
+ }
304
+ async sweepExpired(now = Date.now()) {
305
+ const filter = encodeURIComponent(`expiresAt le ${now}`);
306
+ const url = `${this.baseUrl}/${this.tableName}()?$filter=${filter}`;
307
+ const response = await this.fetchImpl(url, { method: "GET", headers: await this.headers() });
308
+ if (!response.ok) {
309
+ throw new Error(`Table query failed with status ${response.status}.`);
310
+ }
311
+ const body = (await response.json());
312
+ let removed = 0;
313
+ for (const entity of body.value ?? []) {
314
+ await this.delete(entity.RowKey);
315
+ removed += 1;
316
+ }
317
+ return removed;
318
+ }
319
+ }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * Azure Table Storage squad-memory store (shared-state broker — table backend).
3
+ *
4
+ * The file-backed {@link import("../backends/file-squad-memory.js").FileSquadMemoryStore}
5
+ * survives restarts but is single-replica; Azure Table Storage gives a shared,
6
+ * cross-replica store whose optimistic concurrency (ETag `If-Match`) is a true
7
+ * compare-and-swap. This mirrors
8
+ * {@link import("./azure-table-run-state.js").AzureTableRunStateStore}: it talks
9
+ * to the Table REST API with `fetch` and an INJECTED managed-identity token
10
+ * provider, so there is NO Azure SDK dependency and the build/tests stay SDK-free.
11
+ * It is live-only: wired by `server-http.ts`, never imported by a test.
12
+ *
13
+ * Security posture:
14
+ * * Tenant isolation — `PartitionKey = <tenantId>:<project>`, so an entry is
15
+ * physically partitioned by the authenticated tenant; a caller can never read
16
+ * or write another tenant's partition (the `tenantId` is never caller input).
17
+ * * SEC-3 — the storage account + table come from operator config, never a
18
+ * caller; a caller cannot redirect persistence elsewhere.
19
+ * * SEC-4 — `project` / `path` are re-validated as safe segments before they
20
+ * build a PartitionKey / RowKey, so a traversal or injection payload cannot
21
+ * escape the partition.
22
+ * * SEC-10 — the access token is registered with the logger for redaction and
23
+ * never logged; error paths never include the response body.
24
+ * * MEDIUM-3 — `content` is encrypted with the injected {@link FieldCipher}
25
+ * before it leaves the process, so the caller's text is opaque at rest even to
26
+ * an operator with raw table access.
27
+ */
28
+ import { isSafeMemoryPath, isSafeMemorySegment, } from "../squad-memory-state.js";
29
+ import { NullFieldCipher, decryptField, encryptField } from "../field-cipher.js";
30
+ /** The Table REST API version this client speaks. */
31
+ const TABLE_API_VERSION = "2019-02-02";
32
+ export class AzureTableSquadMemoryStore {
33
+ account;
34
+ tableName;
35
+ getAccessToken;
36
+ cipher;
37
+ fetchImpl;
38
+ logger;
39
+ baseUrl;
40
+ /**
41
+ * WI-07 — memoized create-if-not-exists guard. Resolved once the table is known
42
+ * to exist (or was just created); a failure clears it so the next write retries
43
+ * rather than poisoning every subsequent write with a cached rejection.
44
+ */
45
+ tableEnsured;
46
+ constructor(options) {
47
+ this.account = options.account;
48
+ this.tableName = options.tableName;
49
+ this.getAccessToken = options.getAccessToken;
50
+ this.cipher = options.cipher ?? new NullFieldCipher();
51
+ this.fetchImpl = options.fetchImpl ?? fetch;
52
+ this.logger = options.logger;
53
+ const host = options.endpoint ?? `https://${this.account}.table.core.windows.net`;
54
+ this.baseUrl = host.replace(/\/$/, "");
55
+ }
56
+ async headers(extra = {}) {
57
+ const token = await this.getAccessToken();
58
+ this.logger?.registerSecret(token);
59
+ return {
60
+ Authorization: `Bearer ${token}`,
61
+ "x-ms-version": TABLE_API_VERSION,
62
+ "x-ms-date": new Date().toUTCString(),
63
+ Accept: "application/json;odata=nometadata",
64
+ "Content-Type": "application/json",
65
+ ...extra,
66
+ };
67
+ }
68
+ /**
69
+ * WI-07 — idempotently create the backing table before the first write. Issues
70
+ * `POST <baseUrl>/Tables` with `{"TableName": <tableName>}`; a 201/204 means it
71
+ * was created and a 409 means it already exists — both are success. The result
72
+ * is memoized so only the FIRST write pays the round-trip; a failure clears the
73
+ * memo so a later write can retry instead of inheriting a cached rejection.
74
+ * Never called on read / list / listProjects paths (a missing table already
75
+ * yields `[]` / `undefined` there).
76
+ */
77
+ ensureTable() {
78
+ if (this.tableEnsured === undefined) {
79
+ this.tableEnsured = this.createTable().catch((error) => {
80
+ this.tableEnsured = undefined;
81
+ throw error;
82
+ });
83
+ }
84
+ return this.tableEnsured;
85
+ }
86
+ async createTable() {
87
+ const response = await this.fetchImpl(`${this.baseUrl}/Tables`, {
88
+ method: "POST",
89
+ headers: await this.headers({ Prefer: "return-no-content" }),
90
+ body: JSON.stringify({ TableName: this.tableName }),
91
+ });
92
+ // 201/204 -> created; 409 -> already exists. Both mean the table is ready.
93
+ if (response.status === 201 || response.status === 204 || response.status === 409) {
94
+ return;
95
+ }
96
+ throw new Error(`Table create failed with status ${response.status}.`);
97
+ }
98
+ /** The tenant/project partition key (isolation boundary; never caller-derivable). */
99
+ partitionKey(tenantId, project) {
100
+ return `${tenantId}:${project}`;
101
+ } /**
102
+ * The stored RowKey for a memory `path`. Azure Table Storage forbids `/`, `\`,
103
+ * `#`, and `?` in key fields, so a multi-segment family (`history/<agent>`,
104
+ * `repo-memory/<name>`) cannot be stored verbatim. Percent-encoding the path
105
+ * yields a valid RowKey (`/` -> `%2F`) that still round-trips one-to-one with
106
+ * the raw `path`; the raw value is preserved in the entity's `path` property,
107
+ * so reads reconstruct it without decoding the key.
108
+ */
109
+ rowKey(path) {
110
+ return encodeURIComponent(path);
111
+ }
112
+ entityUrl(partitionKey, path) {
113
+ // The RowKey value itself is percent-encoded (see rowKey); the OData URL then
114
+ // percent-encodes that value again for transport, so Azure decodes exactly one
115
+ // layer back to the stored key and no forbidden `/` ever reaches the key field.
116
+ return `${this.baseUrl}/${this.tableName}(PartitionKey='${encodeURIComponent(partitionKey)}',RowKey='${encodeURIComponent(this.rowKey(path))}')`;
117
+ }
118
+ /** Map a wire entity back to a decrypted entry. */
119
+ fromEntity(entity, tenantId) {
120
+ return {
121
+ tenantId,
122
+ project: entity.project,
123
+ path: entity.path,
124
+ content: decryptField(this.cipher, entity.content) ?? "",
125
+ etag: entity["odata.etag"] ?? "",
126
+ updatedAt: entity.updatedAt,
127
+ };
128
+ }
129
+ /** Build the sealed wire entity for a write (content encrypted). */
130
+ toEntity(tenantId, project, path, content) {
131
+ const entity = {
132
+ PartitionKey: this.partitionKey(tenantId, project),
133
+ RowKey: this.rowKey(path),
134
+ project,
135
+ path,
136
+ updatedAt: Date.now(),
137
+ };
138
+ const sealed = encryptField(this.cipher, content);
139
+ if (sealed !== undefined)
140
+ entity.content = sealed;
141
+ return entity;
142
+ }
143
+ async list(tenantId, project) {
144
+ if (!isSafeMemorySegment(tenantId) || !isSafeMemorySegment(project)) {
145
+ return [];
146
+ }
147
+ const filter = `PartitionKey eq '${this.partitionKey(tenantId, project)}'`;
148
+ const url = `${this.baseUrl}/${this.tableName}()?$filter=${encodeURIComponent(filter)}`;
149
+ const response = await this.fetchImpl(url, { method: "GET", headers: await this.headers() });
150
+ if (response.status === 404) {
151
+ return [];
152
+ }
153
+ if (!response.ok) {
154
+ throw new Error(`Table query failed with status ${response.status}.`);
155
+ }
156
+ const body = (await response.json());
157
+ return (body.value ?? []).map((entity) => this.fromEntity(entity, tenantId));
158
+ }
159
+ async read(tenantId, project, path) {
160
+ if (!isSafeMemorySegment(tenantId) || !isSafeMemorySegment(project) || !isSafeMemoryPath(path)) {
161
+ return undefined;
162
+ }
163
+ const entity = await this.fetchEntity(this.partitionKey(tenantId, project), path);
164
+ return entity ? this.fromEntity(entity, tenantId) : undefined;
165
+ }
166
+ /** Fetch the raw (still-sealed) entity + its ETag by exact key. */
167
+ async fetchEntity(partitionKey, path) {
168
+ const response = await this.fetchImpl(this.entityUrl(partitionKey, path), {
169
+ method: "GET",
170
+ headers: await this.headers(),
171
+ });
172
+ if (response.status === 404) {
173
+ return undefined;
174
+ }
175
+ if (!response.ok) {
176
+ throw new Error(`Table read failed with status ${response.status}.`);
177
+ }
178
+ return (await response.json());
179
+ }
180
+ async write(tenantId, project, path, content, expectedEtag) {
181
+ if (!isSafeMemorySegment(tenantId) || !isSafeMemorySegment(project) || !isSafeMemoryPath(path)) {
182
+ // A malformed key never touches storage; treat as a lost race (no leakage).
183
+ return { ok: false, conflict: true, current: undefined };
184
+ }
185
+ // WI-07 — create the backing table on first write (memoized); never on reads.
186
+ await this.ensureTable();
187
+ const partitionKey = this.partitionKey(tenantId, project);
188
+ const entity = this.toEntity(tenantId, project, path, content);
189
+ // Insert-Or-Replace (no If-Match) for a first/unconditional write; Update
190
+ // (If-Match: <etag>) makes a CAS write a true compare-and-swap — a stale etag
191
+ // (or a since-deleted entry) fails 412/404 and we return the current revision.
192
+ const conditional = expectedEtag !== undefined;
193
+ const response = await this.fetchImpl(this.entityUrl(partitionKey, path), {
194
+ method: "PUT",
195
+ headers: await this.headers(conditional ? { "If-Match": expectedEtag } : {}),
196
+ body: JSON.stringify(entity),
197
+ });
198
+ if (conditional && (response.status === 412 || response.status === 404)) {
199
+ const current = await this.fetchEntity(partitionKey, path);
200
+ return { ok: false, conflict: true, current: current ? this.fromEntity(current, tenantId) : undefined };
201
+ }
202
+ if (!response.ok) {
203
+ throw new Error(`Table write failed with status ${response.status}.`);
204
+ }
205
+ const etag = response.headers.get("etag") ?? "";
206
+ return {
207
+ ok: true,
208
+ etag,
209
+ entry: { tenantId, project, path, content, etag, updatedAt: entity.updatedAt },
210
+ };
211
+ }
212
+ async listProjects(tenantId) {
213
+ if (!isSafeMemorySegment(tenantId)) {
214
+ return [];
215
+ }
216
+ // PartitionKey range scan bounded to this tenant: every `tenantId:<project>`
217
+ // sorts >= `tenantId:` and < `tenantId;` (`;` = the codepoint after `:`),
218
+ // so the range selects exactly this tenant's partitions without startswith.
219
+ const lower = `${tenantId}:`;
220
+ const upper = `${tenantId};`;
221
+ const filter = `PartitionKey ge '${lower}' and PartitionKey lt '${upper}'`;
222
+ const url = `${this.baseUrl}/${this.tableName}()?$filter=${encodeURIComponent(filter)}&$select=PartitionKey`;
223
+ const response = await this.fetchImpl(url, { method: "GET", headers: await this.headers() });
224
+ if (response.status === 404) {
225
+ return [];
226
+ }
227
+ if (!response.ok) {
228
+ throw new Error(`Table query failed with status ${response.status}.`);
229
+ }
230
+ const body = (await response.json());
231
+ const projects = new Set();
232
+ for (const row of body.value ?? []) {
233
+ const project = row.PartitionKey.slice(lower.length);
234
+ if (project.length > 0) {
235
+ projects.add(project);
236
+ }
237
+ }
238
+ return [...projects];
239
+ }
240
+ }