@indigoai-us/hq-cloud 6.11.5 → 6.11.6

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 (81) hide show
  1. package/dist/bin/sync-runner.d.ts +16 -16
  2. package/dist/bin/sync-runner.d.ts.map +1 -1
  3. package/dist/bin/sync-runner.js +50 -41
  4. package/dist/bin/sync-runner.js.map +1 -1
  5. package/dist/bin/sync-runner.test.js +107 -33
  6. package/dist/bin/sync-runner.test.js.map +1 -1
  7. package/dist/context.d.ts +6 -0
  8. package/dist/context.d.ts.map +1 -1
  9. package/dist/context.js +57 -17
  10. package/dist/context.js.map +1 -1
  11. package/dist/context.test.js +113 -1
  12. package/dist/context.test.js.map +1 -1
  13. package/dist/entity-resolver.test.js +3 -3
  14. package/dist/entity-resolver.test.js.map +1 -1
  15. package/dist/object-io.d.ts.map +1 -1
  16. package/dist/object-io.js +10 -0
  17. package/dist/object-io.js.map +1 -1
  18. package/dist/signals/get.d.ts.map +1 -1
  19. package/dist/signals/get.js +7 -11
  20. package/dist/signals/get.js.map +1 -1
  21. package/dist/signals/get.test.js +65 -1
  22. package/dist/signals/get.test.js.map +1 -1
  23. package/dist/signals/internals.d.ts +47 -3
  24. package/dist/signals/internals.d.ts.map +1 -1
  25. package/dist/signals/internals.js +110 -4
  26. package/dist/signals/internals.js.map +1 -1
  27. package/dist/signals/list.d.ts.map +1 -1
  28. package/dist/signals/list.js +16 -23
  29. package/dist/signals/list.js.map +1 -1
  30. package/dist/signals/list.test.js +84 -1
  31. package/dist/signals/list.test.js.map +1 -1
  32. package/dist/signals/types.d.ts +18 -1
  33. package/dist/signals/types.d.ts.map +1 -1
  34. package/dist/sources/get.d.ts.map +1 -1
  35. package/dist/sources/get.js +10 -22
  36. package/dist/sources/get.js.map +1 -1
  37. package/dist/sources/get.test.js +85 -1
  38. package/dist/sources/get.test.js.map +1 -1
  39. package/dist/sources/internals.d.ts +50 -3
  40. package/dist/sources/internals.d.ts.map +1 -1
  41. package/dist/sources/internals.js +113 -4
  42. package/dist/sources/internals.js.map +1 -1
  43. package/dist/sources/list.d.ts.map +1 -1
  44. package/dist/sources/list.js +16 -23
  45. package/dist/sources/list.js.map +1 -1
  46. package/dist/sources/list.test.js +101 -1
  47. package/dist/sources/list.test.js.map +1 -1
  48. package/dist/sources/types.d.ts +18 -1
  49. package/dist/sources/types.d.ts.map +1 -1
  50. package/dist/sync/event-sync.d.ts +6 -7
  51. package/dist/sync/event-sync.d.ts.map +1 -1
  52. package/dist/sync/event-sync.js +6 -7
  53. package/dist/sync/event-sync.js.map +1 -1
  54. package/dist/types.d.ts +33 -3
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/version.d.ts +14 -0
  57. package/dist/version.d.ts.map +1 -0
  58. package/dist/version.js +20 -0
  59. package/dist/version.js.map +1 -0
  60. package/package.json +1 -1
  61. package/src/bin/sync-runner.test.ts +130 -41
  62. package/src/bin/sync-runner.ts +55 -48
  63. package/src/context.test.ts +139 -1
  64. package/src/context.ts +59 -17
  65. package/src/entity-resolver.test.ts +3 -3
  66. package/src/object-io.ts +12 -0
  67. package/src/signals/get.test.ts +83 -1
  68. package/src/signals/get.ts +9 -13
  69. package/src/signals/internals.ts +153 -4
  70. package/src/signals/list.test.ts +114 -1
  71. package/src/signals/list.ts +16 -29
  72. package/src/signals/types.ts +18 -1
  73. package/src/sources/get.test.ts +104 -1
  74. package/src/sources/get.ts +12 -24
  75. package/src/sources/internals.ts +156 -4
  76. package/src/sources/list.test.ts +132 -1
  77. package/src/sources/list.ts +16 -29
  78. package/src/sources/types.ts +18 -1
  79. package/src/sync/event-sync.ts +6 -7
  80. package/src/types.ts +33 -3
  81. package/src/version.ts +24 -0
@@ -1,15 +1,34 @@
1
1
  /**
2
2
  * Internal helpers shared between signals/list.ts and signals/get.ts.
3
3
  *
4
- * Independent S3 client factory hook (separate from sources/internals.ts)
5
- * so signals tests can swap their stub without disturbing sources tests.
6
- * Production code never calls the setter.
4
+ * Two transports back the read surface (see sources/internals.ts for the full
5
+ * rationale): the presigned-URL path (a vault client + a company vault, cmp_*)
6
+ * and the direct-S3 path (no vault client, or a personal vault prs_*). The
7
+ * direct-S3 path goes through `getS3Client`, whose factory hook is independent
8
+ * from sources/internals.ts so signals tests can swap their stub without
9
+ * disturbing sources tests.
7
10
  */
8
11
 
9
- import { S3Client } from "@aws-sdk/client-s3";
12
+ import {
13
+ S3Client,
14
+ GetObjectCommand,
15
+ ListObjectsV2Command,
16
+ } from "@aws-sdk/client-s3";
10
17
  import type { EntityContext } from "../types.js";
18
+ import { PresignObjectIO, type PresignTransportClient } from "../object-io.js";
11
19
 
12
20
  function defaultFactory(ctx: EntityContext): S3Client {
21
+ if (!ctx.credentials) {
22
+ // The direct-S3 read path needs STS creds. A credential-less context only
23
+ // exists on the presign path (HQ-59 company vend-skip), which reads via the
24
+ // vault list/presign endpoints, not this S3 client — so arriving here with
25
+ // no creds is a routing bug. Fail loudly rather than 403 opaquely later.
26
+ throw new Error(
27
+ `Signals S3 read for ${ctx.uid} requires STS credentials but got a ` +
28
+ `presign-only context; company presign reads must go through the ` +
29
+ `vault transport, not getS3Client.`,
30
+ );
31
+ }
13
32
  return new S3Client({
14
33
  region: ctx.region,
15
34
  credentials: {
@@ -44,3 +63,133 @@ export async function streamToString(body: unknown): Promise<string> {
44
63
  }
45
64
  return Buffer.concat(chunks).toString("utf-8");
46
65
  }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // Transport seam (presign for cmp_, direct-S3 otherwise)
69
+ // ---------------------------------------------------------------------------
70
+
71
+ /** Common shape of every reader's options: an entity + an optional vault client. */
72
+ export interface ReaderTransportOpts {
73
+ entity: EntityContext;
74
+ /**
75
+ * Presign-capable vault client. When supplied and the entity is a company
76
+ * vault (cmp_*), reads use the presigned-URL transport instead of direct S3.
77
+ */
78
+ vault?: PresignTransportClient;
79
+ }
80
+
81
+ /** Lightweight listed object (transport-agnostic). */
82
+ export interface ListedKey {
83
+ key: string;
84
+ size: number;
85
+ lastModified: Date;
86
+ }
87
+
88
+ /** True when this read should use the presigned-URL transport. */
89
+ export function usePresign(opts: ReaderTransportOpts): boolean {
90
+ return opts.vault != null && opts.entity.uid.startsWith("cmp_");
91
+ }
92
+
93
+ /** A not-found error normalized to the S3 `NoSuchKey` shape callers test for. */
94
+ function noSuchKeyError(key: string): Error {
95
+ return Object.assign(new Error(`No such key: ${key}`), { name: "NoSuchKey" });
96
+ }
97
+
98
+ function isNotFound(err: unknown): boolean {
99
+ if (!err || typeof err !== "object") return false;
100
+ const name = (err as { name?: unknown }).name;
101
+ return (
102
+ name === "NoSuchKey" || name === "NoSuchKeyException" || name === "NotFound"
103
+ );
104
+ }
105
+
106
+ /**
107
+ * Read an object's UTF-8 text. Throws a `NoSuchKey`-named error when the object
108
+ * is absent (both transports), so callers' existing not-found checks work
109
+ * unchanged.
110
+ */
111
+ export async function readObjectText(
112
+ opts: ReaderTransportOpts,
113
+ key: string,
114
+ ): Promise<string> {
115
+ if (usePresign(opts)) {
116
+ const io = new PresignObjectIO(opts.vault!, opts.entity.uid);
117
+ try {
118
+ const { body } = await io.getObject(key);
119
+ return body.toString("utf-8");
120
+ } catch (err) {
121
+ if (isNotFound(err)) throw noSuchKeyError(key);
122
+ throw err;
123
+ }
124
+ }
125
+ const client = getS3Client(opts.entity);
126
+ const res = await client.send(
127
+ new GetObjectCommand({ Bucket: opts.entity.bucketName, Key: key }),
128
+ );
129
+ return streamToString(res.Body);
130
+ }
131
+
132
+ /** Like {@link readObjectText} but returns null when the object is absent. */
133
+ export async function tryReadObjectText(
134
+ opts: ReaderTransportOpts,
135
+ key: string,
136
+ ): Promise<string | null> {
137
+ try {
138
+ return await readObjectText(opts, key);
139
+ } catch (err) {
140
+ if (isNotFound(err)) return null;
141
+ throw err;
142
+ }
143
+ }
144
+
145
+ /**
146
+ * List one page of objects under `prefix`.
147
+ *
148
+ * Under the presigned transport the vault `list` endpoint is ACL-filtered and
149
+ * controls page size server-side, so `limit` is advisory — paginate via the
150
+ * returned `nextToken` (the opaque vault cursor) until it is undefined. Under
151
+ * direct S3, `limit` maps to `MaxKeys`.
152
+ */
153
+ export async function listObjects(
154
+ opts: ReaderTransportOpts,
155
+ prefix: string,
156
+ page: { limit?: number; continuationToken?: string },
157
+ ): Promise<{ contents: ListedKey[]; nextToken?: string }> {
158
+ if (usePresign(opts)) {
159
+ const io = new PresignObjectIO(opts.vault!, opts.entity.uid);
160
+ const res = await io.listObjects({
161
+ prefix,
162
+ continuationToken: page.continuationToken,
163
+ });
164
+ return {
165
+ contents: res.objects.map((o) => ({
166
+ key: o.key,
167
+ size: o.size,
168
+ lastModified: o.lastModified,
169
+ })),
170
+ nextToken: res.nextContinuationToken,
171
+ };
172
+ }
173
+ const client = getS3Client(opts.entity);
174
+ const res = await client.send(
175
+ new ListObjectsV2Command({
176
+ Bucket: opts.entity.bucketName,
177
+ Prefix: prefix,
178
+ MaxKeys: page.limit,
179
+ ContinuationToken: page.continuationToken,
180
+ }),
181
+ );
182
+ const contents: ListedKey[] = [];
183
+ for (const obj of res.Contents ?? []) {
184
+ if (!obj.Key) continue;
185
+ contents.push({
186
+ key: obj.Key,
187
+ size: obj.Size ?? 0,
188
+ lastModified: obj.LastModified ?? new Date(0),
189
+ });
190
+ }
191
+ return {
192
+ contents,
193
+ nextToken: res.IsTruncated ? res.NextContinuationToken : undefined,
194
+ };
195
+ }
@@ -6,7 +6,7 @@
6
6
  * @aws-sdk/client-s3.
7
7
  */
8
8
 
9
- import { describe, it, expect, beforeEach, afterEach } from "vitest";
9
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
10
10
  import {
11
11
  GetObjectCommand,
12
12
  ListObjectsV2Command,
@@ -17,6 +17,8 @@ import {
17
17
  _setSignalsS3Factory,
18
18
  _resetSignalsS3Factory,
19
19
  } from "./internals.js";
20
+ import type { PresignTransportClient } from "../object-io.js";
21
+ import type { VaultListedObject } from "../vault-client.js";
20
22
  import type { EntityContext } from "../types.js";
21
23
  import { InvalidSignalTypeError, SIGNAL_TYPES } from "../schemas/signal-types.js";
22
24
 
@@ -281,3 +283,114 @@ describe("listSignals", () => {
281
283
  expect(observed.commands).toHaveLength(0);
282
284
  });
283
285
  });
286
+
287
+ // ---------------------------------------------------------------------------
288
+ // Presigned transport (vault client + company vault) — HQ-59
289
+ // ---------------------------------------------------------------------------
290
+
291
+ interface PresignVaultStub {
292
+ vault: PresignTransportClient;
293
+ listCalls: Array<{ prefix?: string; cursor?: string }>;
294
+ }
295
+
296
+ function makePresignVault(
297
+ page: { objects: VaultListedObject[]; cursor: string | null },
298
+ contents: Record<string, string> = {},
299
+ ): PresignVaultStub {
300
+ const listCalls: Array<{ prefix?: string; cursor?: string }> = [];
301
+ vi.stubGlobal(
302
+ "fetch",
303
+ vi.fn(async (url: string) => {
304
+ const key = new URL(url).searchParams.get("key") ?? "";
305
+ const c = contents[key];
306
+ if (c === undefined) return new Response(null, { status: 404 });
307
+ return new Response(Buffer.from(c, "utf-8"), { status: 200 });
308
+ }),
309
+ );
310
+ const vault: PresignTransportClient = {
311
+ presign: async (input) => ({
312
+ results: input.keys.map((k) => ({
313
+ key: k.key,
314
+ op: k.op ?? input.op ?? "get",
315
+ url: `https://signed.example/?key=${encodeURIComponent(k.key)}`,
316
+ })),
317
+ expiresAt: "2099-01-01T00:00:00.000Z",
318
+ }),
319
+ listFiles: async (_company, prefix, cursor) => {
320
+ listCalls.push({ prefix, cursor });
321
+ return {
322
+ objects: page.objects,
323
+ cursor: page.cursor,
324
+ truncated: page.cursor != null,
325
+ };
326
+ },
327
+ };
328
+ return { vault, listCalls };
329
+ }
330
+
331
+ function listed(key: string): VaultListedObject {
332
+ return {
333
+ key,
334
+ size: 10,
335
+ lastModified: "2026-03-15T15:00:00.000Z",
336
+ etag: "etag",
337
+ permission: "read",
338
+ };
339
+ }
340
+
341
+ describe("listSignals — presigned transport (vault + cmp_)", () => {
342
+ afterEach(() => vi.unstubAllGlobals());
343
+
344
+ it("lists via the ACL-filtered vault endpoint and never touches S3", async () => {
345
+ _setSignalsS3Factory(
346
+ () =>
347
+ ({
348
+ send: async () => {
349
+ throw new Error("S3 must not be used on the presign path");
350
+ },
351
+ }) as unknown as S3Client,
352
+ );
353
+ const { vault, listCalls } = makePresignVault({
354
+ objects: [listed("signals/action_item/foo.md")],
355
+ cursor: null,
356
+ });
357
+
358
+ const res = await listSignals({
359
+ entity: ENTITY,
360
+ signalType: "action_item",
361
+ vault,
362
+ });
363
+
364
+ expect(res.entries.map((e) => e.signalId)).toEqual(["foo"]);
365
+ expect(res.entries[0].key).toBe("signals/action_item/foo.md");
366
+ expect(res.nextToken).toBeUndefined();
367
+ expect(listCalls[0].prefix).toBe("signals/action_item/");
368
+ });
369
+
370
+ it("surfaces the opaque vault cursor as nextToken", async () => {
371
+ const { vault } = makePresignVault({
372
+ objects: [listed("signals/action_item/foo.md")],
373
+ cursor: "OPAQUE_CURSOR",
374
+ });
375
+ const res = await listSignals({
376
+ entity: ENTITY,
377
+ signalType: "action_item",
378
+ vault,
379
+ });
380
+ expect(res.nextToken).toBe("OPAQUE_CURSOR");
381
+ });
382
+
383
+ it("includeFrontmatter surfaces sourceRef via a presigned GET", async () => {
384
+ const { vault } = makePresignVault(
385
+ { objects: [listed("signals/action_item/foo.md")], cursor: null },
386
+ { "signals/action_item/foo.md": ACTION_ITEM_MD },
387
+ );
388
+ const res = await listSignals({
389
+ entity: ENTITY,
390
+ signalType: "action_item",
391
+ includeFrontmatter: true,
392
+ vault,
393
+ });
394
+ expect(res.entries[0].sourceRef).toBe("abc-meeting-001");
395
+ });
396
+ });
@@ -6,12 +6,8 @@
6
6
  * `includeFrontmatter: true` (otherwise the field is undefined).
7
7
  */
8
8
 
9
- import {
10
- GetObjectCommand,
11
- ListObjectsV2Command,
12
- } from "@aws-sdk/client-s3";
13
9
  import { assertSignalType } from "../schemas/signal-types.js";
14
- import { getS3Client, streamToString } from "./internals.js";
10
+ import { listObjects, readObjectText } from "./internals.js";
15
11
  import { parseFrontmatter } from "./parse.js";
16
12
  import type {
17
13
  ListSignalsOptions,
@@ -31,44 +27,35 @@ function deriveSignalId(key: string, prefix: string): string | null {
31
27
  }
32
28
 
33
29
  export async function listSignals(opts: ListSignalsOptions): Promise<ListSignalsResult> {
34
- // Validate signalType BEFORE any S3 call (acceptance criterion + agent-mitigation).
30
+ // Validate signalType BEFORE any read (acceptance criterion + agent-mitigation).
35
31
  assertSignalType(opts.signalType);
36
32
 
37
- const client = getS3Client(opts.entity);
38
33
  const prefix = `signals/${opts.signalType}/`;
39
34
 
40
- const response = await client.send(
41
- new ListObjectsV2Command({
42
- Bucket: opts.entity.bucketName,
43
- Prefix: prefix,
44
- MaxKeys: opts.limit,
45
- ContinuationToken: opts.continuationToken,
46
- }),
47
- );
35
+ // Presign transport ACL-filters server-side and controls page size, so
36
+ // `limit` is advisory there; under direct S3 it maps to MaxKeys. Paginate via
37
+ // the returned nextToken regardless of transport.
38
+ const page = await listObjects(opts, prefix, {
39
+ limit: opts.limit,
40
+ continuationToken: opts.continuationToken,
41
+ });
48
42
 
49
43
  const entries: SignalSummary[] = [];
50
- for (const obj of response.Contents ?? []) {
51
- if (!obj.Key) continue;
52
- const signalId = deriveSignalId(obj.Key, prefix);
44
+ for (const obj of page.contents) {
45
+ const signalId = deriveSignalId(obj.key, prefix);
53
46
  if (!signalId) continue;
54
47
 
55
48
  const summary: SignalSummary = {
56
49
  signalId,
57
50
  signalType: opts.signalType,
58
- key: obj.Key,
59
- lastModified: obj.LastModified ?? new Date(0),
60
- size: obj.Size ?? 0,
51
+ key: obj.key,
52
+ lastModified: obj.lastModified,
53
+ size: obj.size,
61
54
  };
62
55
 
63
56
  if (opts.includeFrontmatter) {
64
57
  try {
65
- const get = await client.send(
66
- new GetObjectCommand({
67
- Bucket: opts.entity.bucketName,
68
- Key: obj.Key,
69
- }),
70
- );
71
- const text = await streamToString(get.Body);
58
+ const text = await readObjectText(opts, obj.key);
72
59
  const fm = parseFrontmatter(text);
73
60
  if (fm) {
74
61
  summary.frontmatter = fm;
@@ -87,6 +74,6 @@ export async function listSignals(opts: ListSignalsOptions): Promise<ListSignals
87
74
 
88
75
  return {
89
76
  entries,
90
- nextToken: response.IsTruncated ? response.NextContinuationToken : undefined,
77
+ nextToken: page.nextToken,
91
78
  };
92
79
  }
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { SignalType } from "../schemas/signal-types.js";
11
11
  import type { EntityContext } from "../types.js";
12
+ import type { PresignTransportClient } from "../object-io.js";
12
13
 
13
14
  /**
14
15
  * Lightweight summary returned by listSignals(). `frontmatter` and
@@ -53,12 +54,23 @@ export interface SignalDocument {
53
54
  export interface ListSignalsOptions {
54
55
  entity: EntityContext;
55
56
  signalType: SignalType;
56
- /** Max keys per page; defaults to S3 default (1000). */
57
+ /**
58
+ * Max keys per page. Under direct S3 this maps to `MaxKeys`; under the
59
+ * presigned transport ({@link vault} + a company vault) it is advisory — the
60
+ * vault `list` endpoint controls page size server-side. Defaults to the S3
61
+ * default (1000) on the direct path.
62
+ */
57
63
  limit?: number;
58
64
  /** Opaque continuation token returned by a prior page. */
59
65
  continuationToken?: string;
60
66
  /** When true, fetches+parses each entry's frontmatter (extra GETs). */
61
67
  includeFrontmatter?: boolean;
68
+ /**
69
+ * Presign-capable vault client. When supplied and {@link entity} is a company
70
+ * vault (cmp_*), reads use the presigned-URL transport (ACL-filtered, no
71
+ * direct S3). Personal vaults and the absent-client path stay on direct S3.
72
+ */
73
+ vault?: PresignTransportClient;
62
74
  }
63
75
 
64
76
  export interface ListSignalsResult {
@@ -71,4 +83,9 @@ export interface GetSignalOptions {
71
83
  entity: EntityContext;
72
84
  signalType: SignalType;
73
85
  signalId: string;
86
+ /**
87
+ * Presign-capable vault client. When supplied and {@link entity} is a company
88
+ * vault (cmp_*), reads use the presigned-URL transport (no direct S3).
89
+ */
90
+ vault?: PresignTransportClient;
74
91
  }
@@ -2,13 +2,14 @@
2
2
  * Unit tests for sources/get.ts.
3
3
  */
4
4
 
5
- import { describe, it, expect, beforeEach, afterEach } from "vitest";
5
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
6
6
  import { GetObjectCommand, type S3Client } from "@aws-sdk/client-s3";
7
7
  import { getSource, SourceNotFoundError } from "./get.js";
8
8
  import {
9
9
  _setSourcesS3Factory,
10
10
  _resetSourcesS3Factory,
11
11
  } from "./internals.js";
12
+ import type { PresignTransportClient } from "../object-io.js";
12
13
  import type { EntityContext } from "../types.js";
13
14
  import { InvalidSourceChannelError } from "../schemas/source-channels.js";
14
15
 
@@ -164,3 +165,105 @@ describe("getSource", () => {
164
165
  expect(doc.body).toBe("Just a body, no frontmatter.");
165
166
  });
166
167
  });
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Presigned transport (vault client + company vault) — HQ-59
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /**
174
+ * A presign-capable vault stub + a `fetch` mock keyed by the presigned URL.
175
+ * presign() mints a URL that encodes the key; fetch() returns the object's
176
+ * bytes (404 when absent, so a missing key surfaces as SourceNotFoundError —
177
+ * matching the S3 NoSuchKey path).
178
+ */
179
+ function makePresignVault(objects: Record<string, string>): PresignTransportClient {
180
+ vi.stubGlobal(
181
+ "fetch",
182
+ vi.fn(async (url: string) => {
183
+ const key = new URL(url).searchParams.get("key") ?? "";
184
+ const content = objects[key];
185
+ if (content === undefined) return new Response(null, { status: 404 });
186
+ return new Response(Buffer.from(content, "utf-8"), { status: 200 });
187
+ }),
188
+ );
189
+ return {
190
+ presign: async (input) => ({
191
+ results: input.keys.map((k) => ({
192
+ key: k.key,
193
+ op: k.op ?? input.op ?? "get",
194
+ url: `https://signed.example/?key=${encodeURIComponent(k.key)}`,
195
+ })),
196
+ expiresAt: "2099-01-01T00:00:00.000Z",
197
+ }),
198
+ listFiles: async () => ({ objects: [], cursor: null, truncated: false }),
199
+ };
200
+ }
201
+
202
+ describe("getSource — presigned transport (vault + cmp_)", () => {
203
+ afterEach(() => vi.unstubAllGlobals());
204
+
205
+ it("reads via presign and never touches S3", async () => {
206
+ // S3 factory throws if used — proves the read went through presign.
207
+ _setSourcesS3Factory(
208
+ () =>
209
+ ({
210
+ send: async () => {
211
+ throw new Error("S3 must not be used on the presign path");
212
+ },
213
+ }) as unknown as S3Client,
214
+ );
215
+ const vault = makePresignVault({ "sources/meetings/abc.md": MEETING_MD });
216
+
217
+ const doc = await getSource({
218
+ entity: ENTITY,
219
+ channel: "meeting",
220
+ sourceId: "abc",
221
+ vault,
222
+ });
223
+
224
+ expect(doc.frontmatter).toEqual({
225
+ source_id: "abc",
226
+ source_type: "meeting",
227
+ title: "Q1 Planning",
228
+ });
229
+ expect(doc.body).toContain("Body text line 1.");
230
+ });
231
+
232
+ it("maps a presign 404 to SourceNotFoundError", async () => {
233
+ const vault = makePresignVault({});
234
+ await expect(
235
+ getSource({ entity: ENTITY, channel: "meeting", sourceId: "missing", vault }),
236
+ ).rejects.toBeInstanceOf(SourceNotFoundError);
237
+ });
238
+
239
+ it("includeRaw via presign reads the .raw.json sibling", async () => {
240
+ const vault = makePresignVault({
241
+ "sources/meetings/abc.md": MEETING_MD,
242
+ "sources/meetings/abc.raw.json": JSON.stringify(RAW_PAYLOAD),
243
+ });
244
+ const doc = await getSource({
245
+ entity: ENTITY,
246
+ channel: "meeting",
247
+ sourceId: "abc",
248
+ includeRaw: true,
249
+ vault,
250
+ });
251
+ expect(doc.raw).toEqual(RAW_PAYLOAD);
252
+ });
253
+
254
+ it("personal vault (prs_) ignores the vault client and stays on direct S3", async () => {
255
+ // S3 stub serves the doc; the presign fetch would 404 if (wrongly) used.
256
+ installStub({ "sources/meetings/abc.md": MEETING_MD });
257
+ const vault = makePresignVault({});
258
+ const personal: EntityContext = { ...ENTITY, uid: "prs_me" };
259
+
260
+ const doc = await getSource({
261
+ entity: personal,
262
+ channel: "meeting",
263
+ sourceId: "abc",
264
+ vault,
265
+ });
266
+
267
+ expect(doc.body).toContain("Body text line 1.");
268
+ });
269
+ });
@@ -3,9 +3,8 @@
3
3
  * sibling) from an entity bucket and return parsed frontmatter + body.
4
4
  */
5
5
 
6
- import { GetObjectCommand } from "@aws-sdk/client-s3";
7
6
  import { assertSourceChannel, sourcePathSegment } from "../schemas/source-channels.js";
8
- import { getS3Client, streamToString } from "./internals.js";
7
+ import { readObjectText, tryReadObjectText } from "./internals.js";
9
8
  import { parseMarkdown } from "./parse.js";
10
9
  import type { GetSourceOptions, SourceDocument } from "./types.js";
11
10
 
@@ -19,15 +18,18 @@ export class SourceNotFoundError extends Error {
19
18
  function isNoSuchKey(err: unknown): boolean {
20
19
  if (!err || typeof err !== "object") return false;
21
20
  const name = (err as { name?: unknown }).name;
22
- // AWS SDK v3 throws either a `NoSuchKey` exception or a `NotFound` head error.
23
- return name === "NoSuchKey" || name === "NoSuchKeyException";
21
+ // The transport normalizes a missing object to a `NoSuchKey`-named error on
22
+ // both the S3 and presigned paths (a presign 404 → NoSuchKey). `NotFound` is
23
+ // kept for defense in depth (S3 HEAD-style errors).
24
+ return (
25
+ name === "NoSuchKey" || name === "NoSuchKeyException" || name === "NotFound"
26
+ );
24
27
  }
25
28
 
26
29
  export async function getSource(opts: GetSourceOptions): Promise<SourceDocument> {
27
- // Validate channel BEFORE any S3 call (acceptance criterion).
30
+ // Validate channel BEFORE any read (acceptance criterion).
28
31
  assertSourceChannel(opts.channel);
29
32
 
30
- const client = getS3Client(opts.entity);
31
33
  // sources-pipeline writes "meeting" channel to sources/meetings/...; other
32
34
  // channels pass through. See schemas/source-channels.ts:sourcePathSegment.
33
35
  const segment = sourcePathSegment(opts.channel);
@@ -35,13 +37,7 @@ export async function getSource(opts: GetSourceOptions): Promise<SourceDocument>
35
37
 
36
38
  let body: string;
37
39
  try {
38
- const response = await client.send(
39
- new GetObjectCommand({
40
- Bucket: opts.entity.bucketName,
41
- Key: key,
42
- }),
43
- );
44
- body = await streamToString(response.Body);
40
+ body = await readObjectText(opts, key);
45
41
  } catch (err) {
46
42
  if (isNoSuchKey(err)) {
47
43
  throw new SourceNotFoundError(key);
@@ -58,19 +54,11 @@ export async function getSource(opts: GetSourceOptions): Promise<SourceDocument>
58
54
  };
59
55
 
60
56
  if (opts.includeRaw) {
57
+ // Raw sibling is optional; tryReadObjectText returns null when absent.
61
58
  const rawKey = `sources/${segment}/${opts.sourceId}.raw.json`;
62
- try {
63
- const rawResponse = await client.send(
64
- new GetObjectCommand({
65
- Bucket: opts.entity.bucketName,
66
- Key: rawKey,
67
- }),
68
- );
69
- const rawText = await streamToString(rawResponse.Body);
59
+ const rawText = await tryReadObjectText(opts, rawKey);
60
+ if (rawText !== null) {
70
61
  document.raw = JSON.parse(rawText);
71
- } catch (err) {
72
- if (!isNoSuchKey(err)) throw err;
73
- // Raw sibling is optional; leave undefined when absent.
74
62
  }
75
63
  }
76
64