@forwardimpact/libharness 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Dick Olsson
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,42 @@
1
+ import assert from "node:assert";
2
+
3
+ /**
4
+ * Asserts that a function throws with a matching message
5
+ * @param {Function} fn - Function to test
6
+ * @param {RegExp|string} pattern - Pattern to match
7
+ * @param {string} message - Assertion message
8
+ */
9
+ export function assertThrowsMessage(fn, pattern, message) {
10
+ assert.throws(
11
+ fn,
12
+ { message: pattern instanceof RegExp ? pattern : new RegExp(pattern) },
13
+ message,
14
+ );
15
+ }
16
+
17
+ /**
18
+ * Asserts that an async function rejects with a matching message
19
+ * @param {Function} fn - Async function to test
20
+ * @param {RegExp|string} pattern - Pattern to match
21
+ * @param {string} message - Assertion message
22
+ */
23
+ export async function assertRejectsMessage(fn, pattern, message) {
24
+ await assert.rejects(
25
+ fn,
26
+ { message: pattern instanceof RegExp ? pattern : new RegExp(pattern) },
27
+ message,
28
+ );
29
+ }
30
+
31
+ /**
32
+ * Creates a deferred promise for async testing
33
+ * @returns {object} Object with promise, resolve, and reject
34
+ */
35
+ export function createDeferred() {
36
+ let resolve, reject;
37
+ const promise = new Promise((res, rej) => {
38
+ resolve = res;
39
+ reject = rej;
40
+ });
41
+ return { promise, resolve, reject };
42
+ }
@@ -0,0 +1,6 @@
1
+ export {
2
+ assertThrowsMessage,
3
+ assertRejectsMessage,
4
+ createDeferred,
5
+ } from "./assertions.js";
6
+ export * from "./services.js";
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Test fixture utilities for creating dynamic test data
3
+ */
4
+
5
+ /**
6
+ * Creates sample request data for testing
7
+ * @param {object} overrides - Properties to override
8
+ * @returns {object} Test request object
9
+ */
10
+ export function createTestRequest(overrides = {}) {
11
+ return {
12
+ query: "test query",
13
+ userId: "test-user-123",
14
+ sessionId: "test-session-456",
15
+ ...overrides,
16
+ };
17
+ }
18
+
19
+ /**
20
+ * Creates sample vector data for testing
21
+ * @param {number} count - Number of vectors to create
22
+ * @returns {Array} Array of test vectors
23
+ */
24
+ export function createTestVectors(count = 3) {
25
+ return Array.from({ length: count }, (_, i) => ({
26
+ id: `vector-${i}`,
27
+ embedding: Array.from({ length: 384 }, () => Math.random()),
28
+ score: Math.random(),
29
+ }));
30
+ }
31
+
32
+ /**
33
+ * Creates sample message data for testing
34
+ * @param {number} count - Number of messages to create
35
+ * @returns {Array} Array of test messages
36
+ */
37
+ export function createTestMessages(count = 3) {
38
+ const roles = ["system", "user", "assistant"];
39
+ return Array.from({ length: count }, (_, i) => ({
40
+ role: roles[i % 3],
41
+ content: `Test message ${i + 1}`,
42
+ }));
43
+ }
44
+
45
+ /**
46
+ * Creates sample chunk data for testing
47
+ * @param {number} count - Number of chunks to create
48
+ * @returns {Array} Array of test chunks
49
+ */
50
+ export function createTestChunks(count = 3) {
51
+ return Array.from({ length: count }, (_, i) => ({
52
+ id: `chunk-${i}`,
53
+ text: `This is test chunk ${i + 1} with sample content.`,
54
+ tokens: Math.floor(Math.random() * 100) + 10,
55
+ }));
56
+ }
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./fixture/index.js";
2
+ export * from "./mock/index.js";
@@ -0,0 +1,135 @@
1
+ import { mock } from "node:test";
2
+ import { common } from "@forwardimpact/libtype";
3
+
4
+ /**
5
+ * Creates a mock memory client
6
+ * @param {object} overrides - Method overrides
7
+ * @returns {object} Mock memory client
8
+ */
9
+ export function createMockMemoryClient(overrides = {}) {
10
+ return {
11
+ GetWindow: mock.fn(() =>
12
+ Promise.resolve({
13
+ messages: [{ role: "system", content: "You are an assistant" }],
14
+ tools: [],
15
+ }),
16
+ ),
17
+ AppendMemory: mock.fn(() => Promise.resolve({ accepted: "test-id" })),
18
+ ...overrides,
19
+ };
20
+ }
21
+
22
+ /**
23
+ * Creates a mock LLM client
24
+ * @param {object} overrides - Method overrides
25
+ * @returns {object} Mock LLM client
26
+ */
27
+ export function createMockLlmClient(overrides = {}) {
28
+ return {
29
+ CreateCompletions: mock.fn(() =>
30
+ Promise.resolve({
31
+ id: "test-completion",
32
+ choices: [
33
+ {
34
+ message: common.Message.fromObject({
35
+ role: "assistant",
36
+ content: "Test response",
37
+ }),
38
+ },
39
+ ],
40
+ usage: { total_tokens: 100 },
41
+ }),
42
+ ),
43
+ CreateEmbeddings: mock.fn(() =>
44
+ Promise.resolve({
45
+ data: [{ index: 0, embedding: [0.1, 0.2, 0.3] }],
46
+ }),
47
+ ),
48
+ ...overrides,
49
+ };
50
+ }
51
+
52
+ /**
53
+ * Creates a mock agent client
54
+ * @param {object} overrides - Method overrides
55
+ * @returns {object} Mock agent client
56
+ */
57
+ export function createMockAgentClient(overrides = {}) {
58
+ return {
59
+ ProcessUnary: mock.fn(() =>
60
+ Promise.resolve({
61
+ resource_id: "test-conversation",
62
+ choices: [
63
+ {
64
+ message: common.Message.fromObject({
65
+ role: "assistant",
66
+ content: "Test response",
67
+ }),
68
+ },
69
+ ],
70
+ }),
71
+ ),
72
+ ProcessStream: mock.fn(),
73
+ ...overrides,
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Creates a mock trace client
79
+ * @param {object} overrides - Method overrides
80
+ * @returns {object} Mock trace client
81
+ */
82
+ export function createMockTraceClient(overrides = {}) {
83
+ return {
84
+ RecordSpan: mock.fn(() => Promise.resolve()),
85
+ ...overrides,
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Creates a mock vector client
91
+ * @param {object} overrides - Method overrides
92
+ * @returns {object} Mock vector client
93
+ */
94
+ export function createMockVectorClient(overrides = {}) {
95
+ return {
96
+ SearchContent: mock.fn(() =>
97
+ Promise.resolve({
98
+ identifiers: [],
99
+ }),
100
+ ),
101
+ ...overrides,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * Creates a mock graph client
107
+ * @param {object} overrides - Method overrides
108
+ * @returns {object} Mock graph client
109
+ */
110
+ export function createMockGraphClient(overrides = {}) {
111
+ return {
112
+ QueryByPattern: mock.fn(() =>
113
+ Promise.resolve({
114
+ identifiers: [],
115
+ }),
116
+ ),
117
+ ...overrides,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Creates a mock tool client
123
+ * @param {object} overrides - Method overrides
124
+ * @returns {object} Mock tool client
125
+ */
126
+ export function createMockToolClient(overrides = {}) {
127
+ return {
128
+ CallTool: mock.fn(() =>
129
+ Promise.resolve({
130
+ content: "Tool result",
131
+ }),
132
+ ),
133
+ ...overrides,
134
+ };
135
+ }
package/mock/config.js ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Creates a mock configuration object
3
+ * @param {string} name - Service/extension name
4
+ * @param {object} overrides - Properties to override
5
+ * @returns {object} Mock config
6
+ */
7
+ export function createMockConfig(name = "test-service", overrides = {}) {
8
+ return {
9
+ name,
10
+ namespace: "test",
11
+ host: "0.0.0.0",
12
+ port: 3000,
13
+ max_tokens: 4096,
14
+ ...overrides,
15
+ };
16
+ }
17
+
18
+ /**
19
+ * Creates a mock service config with common service properties
20
+ * @param {string} name - Service name
21
+ * @param {object} overrides - Properties to override
22
+ * @returns {object} Mock service config
23
+ */
24
+ export function createMockServiceConfig(name, overrides = {}) {
25
+ return createMockConfig(name, {
26
+ budget: 1000,
27
+ threshold: 0.3,
28
+ limit: 10,
29
+ ...overrides,
30
+ });
31
+ }
32
+
33
+ /**
34
+ * Creates a mock extension config
35
+ * @param {string} name - Extension name
36
+ * @param {object} overrides - Properties to override
37
+ * @returns {object} Mock extension config
38
+ */
39
+ export function createMockExtensionConfig(name, overrides = {}) {
40
+ return createMockConfig(name, {
41
+ secret: "test-secret",
42
+ llmToken: async () => "test-llm-token",
43
+ ...overrides,
44
+ });
45
+ }
package/mock/data.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Shared test data for common testing scenarios
3
+ */
4
+
5
+ // Sample request data
6
+ export const testRequestData = {
7
+ query: "test query",
8
+ userId: "test-user-123",
9
+ sessionId: "test-session-456",
10
+ };
11
+
12
+ // Sample vector data
13
+ export const testVectorData = [
14
+ { id: "vector-1", embedding: [0.1, 0.2, 0.3], score: 0.9 },
15
+ { id: "vector-2", embedding: [0.4, 0.5, 0.6], score: 0.8 },
16
+ { id: "vector-3", embedding: [0.7, 0.8, 0.9], score: 0.7 },
17
+ ];
18
+
19
+ // Sample message data
20
+ export const testMessageData = [
21
+ { role: "system", content: "You are a helpful assistant." },
22
+ { role: "user", content: "Hello, how are you?" },
23
+ { role: "assistant", content: "I'm doing well, thank you for asking!" },
24
+ ];
25
+
26
+ // Sample chunk data
27
+ export const testChunkData = [
28
+ {
29
+ id: "chunk-1",
30
+ text: "This is a sample text chunk for testing purposes.",
31
+ tokens: 10,
32
+ },
33
+ {
34
+ id: "chunk-2",
35
+ text: "Another sample chunk with different content.",
36
+ tokens: 8,
37
+ },
38
+ ];
39
+
40
+ // Sample configuration data
41
+ export const testConfigData = {
42
+ host: "localhost",
43
+ port: 3000,
44
+ threshold: 0.5,
45
+ limit: 100,
46
+ };
package/mock/grpc.js ADDED
@@ -0,0 +1,95 @@
1
+ import { mock } from "node:test";
2
+
3
+ /**
4
+ * Creates a mock gRPC factory function
5
+ * @param {object} overrides - Method overrides
6
+ * @returns {Function} Mock gRPC factory
7
+ */
8
+ export function createMockGrpcFn(overrides = {}) {
9
+ const mockGrpc = {
10
+ Server: function () {
11
+ return {
12
+ addService: mock.fn(),
13
+ bindAsync: mock.fn((uri, creds, callback) => callback(null, 5000)),
14
+ tryShutdown: mock.fn((callback) => callback()),
15
+ ...overrides.server,
16
+ };
17
+ },
18
+ loadPackageDefinition: mock.fn(() => ({
19
+ test: { Test: { service: {} } },
20
+ })),
21
+ makeGenericClientConstructor: mock.fn(() => function () {}),
22
+ ServerCredentials: {
23
+ createInsecure: mock.fn(),
24
+ },
25
+ credentials: {
26
+ createInsecure: mock.fn(),
27
+ },
28
+ status: {
29
+ OK: 0,
30
+ CANCELLED: 1,
31
+ UNKNOWN: 2,
32
+ INVALID_ARGUMENT: 3,
33
+ DEADLINE_EXCEEDED: 4,
34
+ NOT_FOUND: 5,
35
+ ALREADY_EXISTS: 6,
36
+ PERMISSION_DENIED: 7,
37
+ RESOURCE_EXHAUSTED: 8,
38
+ FAILED_PRECONDITION: 9,
39
+ ABORTED: 10,
40
+ OUT_OF_RANGE: 11,
41
+ UNIMPLEMENTED: 12,
42
+ INTERNAL: 13,
43
+ UNAVAILABLE: 14,
44
+ DATA_LOSS: 15,
45
+ UNAUTHENTICATED: 16,
46
+ },
47
+ ...overrides.grpc,
48
+ };
49
+
50
+ const mockProtoLoader = {
51
+ loadSync: mock.fn(() => ({})),
52
+ ...overrides.protoLoader,
53
+ };
54
+
55
+ return () => ({ grpc: mockGrpc, protoLoader: mockProtoLoader });
56
+ }
57
+
58
+ /**
59
+ * Creates a mock gRPC Metadata class
60
+ */
61
+ export class MockMetadata {
62
+ /**
63
+ * Creates a new MockMetadata instance
64
+ */
65
+ constructor() {
66
+ this.data = new Map();
67
+ }
68
+
69
+ /**
70
+ * Sets a metadata key-value pair
71
+ * @param {string} key - The metadata key
72
+ * @param {string} value - The metadata value
73
+ */
74
+ set(key, value) {
75
+ this.data.set(key, value);
76
+ }
77
+
78
+ /**
79
+ * Gets metadata value by key
80
+ * @param {string} key - The metadata key
81
+ * @returns {string[]} Array containing the value, or empty array if not found
82
+ */
83
+ get(key) {
84
+ const value = this.data.get(key);
85
+ return value !== undefined ? [value] : [];
86
+ }
87
+
88
+ /**
89
+ * Returns all metadata as a plain object
90
+ * @returns {object} Object with all metadata key-value pairs
91
+ */
92
+ getMap() {
93
+ return Object.fromEntries(this.data);
94
+ }
95
+ }
package/mock/http.js ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Creates a mock HTTP request with event emitter behavior
3
+ * @param {object} options - Request options
4
+ * @returns {object} Mock request
5
+ */
6
+ export function createMockRequest(options = {}) {
7
+ const { method = "GET", url = "/", body = {}, headers = {} } = options;
8
+
9
+ const bodyStr = JSON.stringify(body);
10
+ let dataCallback;
11
+ let endCallback;
12
+ let errorCallback;
13
+
14
+ return {
15
+ method,
16
+ url,
17
+ headers,
18
+ on(event, callback) {
19
+ if (event === "data") dataCallback = callback;
20
+ if (event === "end") endCallback = callback;
21
+ if (event === "error") errorCallback = callback;
22
+ },
23
+ simulateBody() {
24
+ if (dataCallback) dataCallback(bodyStr);
25
+ if (endCallback) endCallback();
26
+ },
27
+ simulateError(err) {
28
+ if (errorCallback) errorCallback(err);
29
+ },
30
+ };
31
+ }
32
+
33
+ /**
34
+ * Creates a mock HTTP response with tracking
35
+ * @returns {object} Mock response
36
+ */
37
+ export function createMockResponse() {
38
+ const response = {
39
+ headersSent: false,
40
+ statusCode: null,
41
+ headers: {},
42
+ body: "",
43
+ chunks: [],
44
+ writeHead(status, headers) {
45
+ response.statusCode = status;
46
+ response.headers = headers || {};
47
+ response.headersSent = true;
48
+ },
49
+ write(data) {
50
+ response.chunks.push(data);
51
+ },
52
+ end(data) {
53
+ response.body = data || "";
54
+ },
55
+ getBody() {
56
+ return response.chunks.join("") + response.body;
57
+ },
58
+ };
59
+ return response;
60
+ }
package/mock/index.js ADDED
@@ -0,0 +1,26 @@
1
+ export {
2
+ createMockConfig,
3
+ createMockServiceConfig,
4
+ createMockExtensionConfig,
5
+ } from "./config.js";
6
+ export { createMockStorage, MockStorage } from "./storage.js";
7
+ export { createMockLogger, createSilentLogger } from "./logger.js";
8
+ export { createMockGrpcFn, MockMetadata } from "./grpc.js";
9
+ export { createMockRequest, createMockResponse } from "./http.js";
10
+ export {
11
+ createMockObserverFn,
12
+ createMockTracer,
13
+ createMockAuthFn,
14
+ } from "./observer.js";
15
+
16
+ export { createMockResourceIndex } from "./resource-index.js";
17
+ export {
18
+ createMockMemoryClient,
19
+ createMockLlmClient,
20
+ createMockAgentClient,
21
+ createMockTraceClient,
22
+ createMockVectorClient,
23
+ createMockGraphClient,
24
+ createMockToolClient,
25
+ } from "./clients.js";
26
+ export { createMockServiceCallbacks } from "./service-callbacks.js";
package/mock/logger.js ADDED
@@ -0,0 +1,43 @@
1
+ import { mock } from "node:test";
2
+
3
+ /**
4
+ * Creates a mock logger with call tracking
5
+ * @param {object} options - Logger options
6
+ * @param {boolean} options.captureOutput - Whether to capture log output
7
+ * @returns {object} Mock logger
8
+ */
9
+ export function createMockLogger(options = {}) {
10
+ const logs = [];
11
+ const capture = options.captureOutput ?? false;
12
+
13
+ const createMethod = (level) =>
14
+ mock.fn((appId, msg, attributes) => {
15
+ if (capture) {
16
+ logs.push({ level, appId, msg, attributes });
17
+ }
18
+ });
19
+
20
+ return {
21
+ logs,
22
+ debug: createMethod("debug"),
23
+ info: createMethod("info"),
24
+ warn: createMethod("warn"),
25
+ error: createMethod("error"),
26
+ exception: createMethod("exception"),
27
+ };
28
+ }
29
+
30
+ /**
31
+ * Creates a silent logger that does nothing
32
+ * @returns {object} Silent logger
33
+ */
34
+ export function createSilentLogger() {
35
+ const noop = () => {};
36
+ return {
37
+ debug: noop,
38
+ info: noop,
39
+ warn: noop,
40
+ error: noop,
41
+ exception: noop,
42
+ };
43
+ }
@@ -0,0 +1,75 @@
1
+ import { mock } from "node:test";
2
+
3
+ /**
4
+ * Creates a mock observer factory
5
+ * @param {object} logger - Logger to use (optional)
6
+ * @returns {Function} Mock observer factory
7
+ */
8
+ export function createMockObserverFn(logger = null) {
9
+ const mockLogger = logger || {
10
+ debug: mock.fn(),
11
+ info: mock.fn(),
12
+ error: mock.fn(),
13
+ };
14
+
15
+ return () => ({
16
+ observeServerUnaryCall: async (_method, handler, call, callback) => {
17
+ return await handler(call, callback);
18
+ },
19
+ observeClientUnaryCall: async (_method, _request, fn) => {
20
+ return await fn();
21
+ },
22
+ observeClientStreamingCall: (_method, _request, fn) => {
23
+ return fn();
24
+ },
25
+ logger: () => mockLogger,
26
+ });
27
+ }
28
+
29
+ /**
30
+ * Creates a mock tracer
31
+ * @param {object} overrides - Method overrides
32
+ * @returns {object} Mock tracer
33
+ */
34
+ export function createMockTracer(overrides = {}) {
35
+ return {
36
+ startSpan: mock.fn((name, options = {}) => ({
37
+ span_id: `span-${Date.now()}`,
38
+ trace_id: `trace-${Date.now()}`,
39
+ name,
40
+ ...options,
41
+ })),
42
+ startClientSpan: mock.fn((_service, _method) => ({
43
+ span: {
44
+ span_id: `client-span-${Date.now()}`,
45
+ trace_id: `trace-${Date.now()}`,
46
+ },
47
+ metadata: { get: () => [], set: () => {} },
48
+ })),
49
+ startServerSpan: mock.fn((_service, _method, _request, metadata) => ({
50
+ span_id: `server-span-${Date.now()}`,
51
+ trace_id: metadata?.get?.("x-trace-id")?.[0] || `trace-${Date.now()}`,
52
+ })),
53
+ getSpanContext: () => ({
54
+ run: (span, fn) => fn(),
55
+ getStore: () => null,
56
+ }),
57
+ endSpan: mock.fn(),
58
+ recordError: mock.fn(),
59
+ ...overrides,
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Creates a mock auth factory
65
+ * @param {object} options - Auth options
66
+ * @returns {Function} Mock auth factory
67
+ */
68
+ export function createMockAuthFn(options = {}) {
69
+ const { isValid = true, serviceId = "test" } = options;
70
+
71
+ return () => ({
72
+ createClientInterceptor: () => () => {},
73
+ validateCall: () => ({ isValid, serviceId }),
74
+ });
75
+ }
@@ -0,0 +1,110 @@
1
+ import { common, tool } from "@forwardimpact/libtype";
2
+
3
+ /**
4
+ * Creates a mock resource index with common test data
5
+ * @param {object} options - Setup options
6
+ * @returns {object} Mock resource index
7
+ */
8
+ export function createMockResourceIndex(options = {}) {
9
+ const resources = new Map();
10
+
11
+ const index = {
12
+ resources,
13
+
14
+ async get(identifiers, _actor) {
15
+ if (!identifiers || identifiers.length === 0) return [];
16
+ return identifiers
17
+ .map((id) => {
18
+ const key = typeof id === "string" ? id : id.toString?.() || id.name;
19
+ return resources.get(key);
20
+ })
21
+ .filter(Boolean);
22
+ },
23
+
24
+ put(resource) {
25
+ const key = resource.id?.toString?.() || resource.id?.name;
26
+ if (key) resources.set(key, resource);
27
+ },
28
+
29
+ async has(id) {
30
+ const key = typeof id === "string" ? id : id.toString?.();
31
+ return resources.has(key);
32
+ },
33
+
34
+ /**
35
+ * Sets up default test resources
36
+ * @param {object} setupOptions - Setup options
37
+ * @param {string[]} [setupOptions.tools] - Tool names for agent
38
+ * @param {string} [setupOptions.conversationId] - Conversation ID
39
+ * @param {string} [setupOptions.agentId] - Agent ID
40
+ */
41
+ setupDefaults(setupOptions = {}) {
42
+ const {
43
+ tools = [],
44
+ conversationId = "test-conversation",
45
+ agentId = "test-agent",
46
+ } = setupOptions;
47
+
48
+ resources.set(
49
+ conversationId,
50
+ common.Conversation.fromObject({
51
+ id: { name: conversationId },
52
+ agent_id: `common.Agent.${agentId}`,
53
+ }),
54
+ );
55
+
56
+ resources.set(
57
+ `common.Agent.${agentId}`,
58
+ common.Agent.fromObject({
59
+ id: { name: agentId, tokens: 50 },
60
+ tools,
61
+ content: "You are a test agent.",
62
+ }),
63
+ );
64
+
65
+ for (const name of tools) {
66
+ resources.set(
67
+ `tool.ToolFunction.${name}`,
68
+ tool.ToolFunction.fromObject({
69
+ id: { name, tokens: 20 },
70
+ name,
71
+ description: `${name} tool`,
72
+ }),
73
+ );
74
+ }
75
+ },
76
+
77
+ /**
78
+ * Adds a message resource
79
+ * @param {object} msg - Message to add
80
+ */
81
+ addMessage(msg) {
82
+ const id =
83
+ msg.id?.type && msg.id?.toString
84
+ ? msg.id.toString()
85
+ : msg.id?.name || String(msg.id);
86
+ resources.set(id, msg);
87
+ },
88
+
89
+ /**
90
+ * Find resources by prefix
91
+ * @param {string} prefix - Prefix to search for
92
+ * @returns {Promise<string[]>} List of matching keys
93
+ */
94
+ async findByPrefix(prefix) {
95
+ const keys = [];
96
+ for (const key of resources.keys()) {
97
+ if (key.startsWith(prefix)) {
98
+ keys.push(key);
99
+ }
100
+ }
101
+ return keys;
102
+ },
103
+ };
104
+
105
+ if (options.tools || options.conversationId || options.agentId) {
106
+ index.setupDefaults(options);
107
+ }
108
+
109
+ return index;
110
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Creates a mock service callbacks object for agent testing
3
+ * @param {object} overrides - Method overrides per service
4
+ * @returns {object} Service callbacks object
5
+ */
6
+ export function createMockServiceCallbacks(overrides = {}) {
7
+ return {
8
+ memory: {
9
+ append: async () => ({}),
10
+ get: async () => ({
11
+ messages: [{ role: "system", content: "You are an assistant" }],
12
+ tools: [],
13
+ }),
14
+ ...overrides.memory,
15
+ },
16
+ llm: {
17
+ createCompletions: async () => ({
18
+ choices: [
19
+ {
20
+ message: {
21
+ role: "assistant",
22
+ content: "Test response",
23
+ tool_calls: [],
24
+ },
25
+ },
26
+ ],
27
+ }),
28
+ ...overrides.llm,
29
+ },
30
+ tool: {
31
+ call: async () => ({
32
+ role: "tool",
33
+ content: "Tool result",
34
+ }),
35
+ ...overrides.tool,
36
+ },
37
+ ...overrides,
38
+ };
39
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Mock service utilities for testing
3
+ */
4
+
5
+ /**
6
+ * Creates a mock vector service
7
+ * @param {object} overrides - Properties to override in the mock
8
+ * @returns {object} Mock vector service
9
+ */
10
+ export function mockVectorService(overrides = {}) {
11
+ return {
12
+ QueryItems: async (request, callback) => {
13
+ callback(null, { results: [], total: 0 });
14
+ },
15
+ close: () => {},
16
+ ...overrides,
17
+ };
18
+ }
19
+
20
+ /**
21
+ * Creates a mock history service
22
+ * @param {object} overrides - Properties to override in the mock
23
+ * @returns {object} Mock history service
24
+ */
25
+ export function mockHistoryService(overrides = {}) {
26
+ return {
27
+ GetHistory: async (request, callback) => {
28
+ callback(null, { messages: [] });
29
+ },
30
+ UpdateHistory: async (request, callback) => {
31
+ callback(null, {});
32
+ },
33
+ close: () => {},
34
+ ...overrides,
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Creates a mock LLM service
40
+ * @param {object} overrides - Properties to override in the mock
41
+ * @returns {object} Mock LLM service
42
+ */
43
+ export function mockLlmService(overrides = {}) {
44
+ return {
45
+ CreateCompletions: async (request, callback) => {
46
+ callback(null, {
47
+ choices: [
48
+ {
49
+ index: 0,
50
+ message: { role: "assistant", content: "Test response" },
51
+ finish_reason: "stop",
52
+ },
53
+ ],
54
+ });
55
+ },
56
+ CreateEmbeddings: async (request, callback) => {
57
+ callback(null, {
58
+ data: [{ index: 0, embedding: [0.1, 0.2, 0.3] }],
59
+ });
60
+ },
61
+ close: () => {},
62
+ ...overrides,
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Creates a mock text service
68
+ * @param {object} overrides - Properties to override in the mock
69
+ * @returns {object} Mock text service
70
+ */
71
+ export function mockTextService(overrides = {}) {
72
+ return {
73
+ GetChunks: async (request, callback) => {
74
+ callback(null, { chunks: {} });
75
+ },
76
+ close: () => {},
77
+ ...overrides,
78
+ };
79
+ }
@@ -0,0 +1,119 @@
1
+ import { mock } from "node:test";
2
+
3
+ /**
4
+ * Creates a mock storage instance with tracking
5
+ * @param {object} overrides - Method overrides
6
+ * @returns {object} Mock storage with data tracking
7
+ */
8
+ export function createMockStorage(overrides = {}) {
9
+ const data = new Map();
10
+
11
+ return {
12
+ data,
13
+ exists: mock.fn((key) => Promise.resolve(data.has(key))),
14
+ get: mock.fn((key) => {
15
+ const value = data.get(key);
16
+ if (!value) return Promise.reject(new Error("Not found"));
17
+
18
+ if (key.endsWith(".json")) {
19
+ return Promise.resolve(value ? JSON.parse(value) : {});
20
+ }
21
+ if (key.endsWith(".jsonl")) {
22
+ const lines = value.split("\n").filter(Boolean);
23
+ return Promise.resolve(lines.map((line) => JSON.parse(line)));
24
+ }
25
+ return Promise.resolve(value);
26
+ }),
27
+ put: mock.fn((key, value) => {
28
+ data.set(key, value);
29
+ return Promise.resolve();
30
+ }),
31
+ append: mock.fn((key, value) => {
32
+ const existing = data.get(key) || "";
33
+ data.set(key, existing ? `${existing}\n${value}` : value);
34
+ return Promise.resolve();
35
+ }),
36
+ delete: mock.fn((key) => {
37
+ data.delete(key);
38
+ return Promise.resolve();
39
+ }),
40
+ findByPrefix: mock.fn(() => Promise.resolve([])),
41
+ ...overrides,
42
+ };
43
+ }
44
+
45
+ /**
46
+ * MockStorage class for OOP-style usage
47
+ */
48
+ export class MockStorage {
49
+ /**
50
+ * Creates a new MockStorage instance
51
+ */
52
+ constructor() {
53
+ this.data = new Map();
54
+ }
55
+
56
+ /**
57
+ * Gets a value by key
58
+ * @param {string} key - The storage key
59
+ * @returns {Promise<*>} The stored value
60
+ */
61
+ async get(key) {
62
+ const value = this.data.get(key);
63
+ if (!value) throw new Error("Not found");
64
+
65
+ if (key.endsWith(".jsonl")) {
66
+ return value.split("\n").map((line) => JSON.parse(line));
67
+ }
68
+ return value;
69
+ }
70
+
71
+ /**
72
+ * Stores a value by key
73
+ * @param {string} key - The storage key
74
+ * @param {*} value - The value to store
75
+ * @returns {Promise<void>}
76
+ */
77
+ async put(key, value) {
78
+ this.data.set(key, value);
79
+ }
80
+
81
+ /**
82
+ * Alias for put - stores a value by key
83
+ * @param {string} key - The storage key
84
+ * @param {*} value - The value to store
85
+ * @returns {Promise<void>}
86
+ */
87
+ async set(key, value) {
88
+ this.data.set(key, value);
89
+ }
90
+
91
+ /**
92
+ * Appends a value to an existing key
93
+ * @param {string} key - The storage key
94
+ * @param {string} value - The value to append
95
+ * @returns {Promise<void>}
96
+ */
97
+ async append(key, value) {
98
+ const existing = this.data.get(key) || "";
99
+ this.data.set(key, existing ? `${existing}\n${value}` : value);
100
+ }
101
+
102
+ /**
103
+ * Checks if a key exists
104
+ * @param {string} key - The storage key
105
+ * @returns {Promise<boolean>} True if key exists
106
+ */
107
+ async exists(key) {
108
+ return this.data.has(key);
109
+ }
110
+
111
+ /**
112
+ * Deletes a value by key
113
+ * @param {string} key - The storage key
114
+ * @returns {Promise<void>}
115
+ */
116
+ async delete(key) {
117
+ this.data.delete(key);
118
+ }
119
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@forwardimpact/libharness",
3
+ "version": "0.1.5",
4
+ "description": "Test harness and mock infrastructure for guide tests",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./mock": "./mock/index.js",
10
+ "./fixture": "./fixture/index.js"
11
+ },
12
+ "files": [
13
+ "index.js",
14
+ "mock/**/*.js",
15
+ "fixture/**/*.js",
16
+ "README.md"
17
+ ],
18
+ "scripts": {
19
+ "test": "node --test test/*.test.js"
20
+ },
21
+ "keywords": [
22
+ "test",
23
+ "mock",
24
+ "fixture",
25
+ "harness"
26
+ ],
27
+ "author": "Forward Impact Team",
28
+ "license": "MIT",
29
+ "peerDependencies": {
30
+ "@forwardimpact/libtype": "*"
31
+ }
32
+ }