@sidurijs/core 1.0.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 (103) hide show
  1. package/dist/action-executor.d.ts +12 -0
  2. package/dist/action-executor.js +54 -0
  3. package/dist/action-policy.d.ts +79 -0
  4. package/dist/action-policy.js +439 -0
  5. package/dist/action-policy.test.d.ts +1 -0
  6. package/dist/action-policy.test.js +363 -0
  7. package/dist/action.d.ts +72 -0
  8. package/dist/action.js +2 -0
  9. package/dist/adversarial.test.d.ts +1 -0
  10. package/dist/adversarial.test.js +491 -0
  11. package/dist/architecture-boundary.test.d.ts +1 -0
  12. package/dist/architecture-boundary.test.js +108 -0
  13. package/dist/capability.d.ts +78 -0
  14. package/dist/capability.js +168 -0
  15. package/dist/capability.test.d.ts +1 -0
  16. package/dist/capability.test.js +311 -0
  17. package/dist/chat-contract.d.ts +94 -0
  18. package/dist/chat-contract.js +104 -0
  19. package/dist/cognition-planner.d.ts +15 -0
  20. package/dist/cognition-planner.js +23 -0
  21. package/dist/container.d.ts +74 -0
  22. package/dist/container.js +81 -0
  23. package/dist/context-retriever.d.ts +33 -0
  24. package/dist/context-retriever.js +260 -0
  25. package/dist/context.d.ts +46 -0
  26. package/dist/context.js +85 -0
  27. package/dist/context.test.d.ts +1 -0
  28. package/dist/context.test.js +76 -0
  29. package/dist/conversational-teach.test.d.ts +1 -0
  30. package/dist/conversational-teach.test.js +941 -0
  31. package/dist/database.d.ts +1 -0
  32. package/dist/database.js +17 -0
  33. package/dist/dispatcher.d.ts +14 -0
  34. package/dist/dispatcher.js +40 -0
  35. package/dist/dispatcher.test.d.ts +1 -0
  36. package/dist/dispatcher.test.js +58 -0
  37. package/dist/ear-types.d.ts +33 -0
  38. package/dist/ear-types.js +2 -0
  39. package/dist/evidence.d.ts +76 -0
  40. package/dist/evidence.js +27 -0
  41. package/dist/evidence.test.d.ts +1 -0
  42. package/dist/evidence.test.js +75 -0
  43. package/dist/experience-emitter.d.ts +21 -0
  44. package/dist/experience-emitter.js +47 -0
  45. package/dist/experience.d.ts +55 -0
  46. package/dist/experience.js +74 -0
  47. package/dist/experience.test.d.ts +1 -0
  48. package/dist/experience.test.js +55 -0
  49. package/dist/gating.d.ts +45 -0
  50. package/dist/gating.js +185 -0
  51. package/dist/gating.test.d.ts +1 -0
  52. package/dist/gating.test.js +186 -0
  53. package/dist/index.d.ts +367 -0
  54. package/dist/index.js +56 -0
  55. package/dist/input-normalizer.d.ts +14 -0
  56. package/dist/input-normalizer.js +76 -0
  57. package/dist/input-normalizer.test.d.ts +1 -0
  58. package/dist/input-normalizer.test.js +48 -0
  59. package/dist/intent-classifier.d.ts +37 -0
  60. package/dist/intent-classifier.js +150 -0
  61. package/dist/intent-classifier.test.d.ts +1 -0
  62. package/dist/intent-classifier.test.js +118 -0
  63. package/dist/memory-settler.d.ts +49 -0
  64. package/dist/memory-settler.js +161 -0
  65. package/dist/mouth-types.d.ts +90 -0
  66. package/dist/mouth-types.js +2 -0
  67. package/dist/perception-cycle.test.d.ts +1 -0
  68. package/dist/perception-cycle.test.js +301 -0
  69. package/dist/perception-pipeline.d.ts +77 -0
  70. package/dist/perception-pipeline.js +304 -0
  71. package/dist/perception-pipeline.test.d.ts +1 -0
  72. package/dist/perception-pipeline.test.js +65 -0
  73. package/dist/prompt-compiler.d.ts +26 -0
  74. package/dist/prompt-compiler.js +81 -0
  75. package/dist/prompt-compiler.test.d.ts +1 -0
  76. package/dist/prompt-compiler.test.js +90 -0
  77. package/dist/proposals.d.ts +33 -0
  78. package/dist/proposals.js +2 -0
  79. package/dist/response-envelope.d.ts +30 -0
  80. package/dist/response-envelope.js +90 -0
  81. package/dist/runtime-facades.test.d.ts +1 -0
  82. package/dist/runtime-facades.test.js +95 -0
  83. package/dist/runtime.d.ts +116 -0
  84. package/dist/runtime.js +778 -0
  85. package/dist/schema-validator.d.ts +9 -0
  86. package/dist/schema-validator.js +107 -0
  87. package/dist/schema-validator.test.d.ts +1 -0
  88. package/dist/schema-validator.test.js +124 -0
  89. package/dist/session-history.d.ts +20 -0
  90. package/dist/session-history.js +55 -0
  91. package/dist/session-history.test.d.ts +1 -0
  92. package/dist/session-history.test.js +38 -0
  93. package/dist/siduri-db.d.ts +235 -0
  94. package/dist/siduri-db.js +1405 -0
  95. package/dist/siduri-db.test.d.ts +1 -0
  96. package/dist/siduri-db.test.js +1021 -0
  97. package/dist/sqlite-action-store.d.ts +21 -0
  98. package/dist/sqlite-action-store.js +281 -0
  99. package/dist/sqlite-action-store.test.d.ts +1 -0
  100. package/dist/sqlite-action-store.test.js +261 -0
  101. package/dist/teaching.d.ts +14 -0
  102. package/dist/teaching.js +14 -0
  103. package/package.json +43 -0
package/dist/gating.js ADDED
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ResponseGatingEngine = void 0;
4
+ const evidence_1 = require("./evidence");
5
+ function generateId(prefix) {
6
+ return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
7
+ }
8
+ class ResponseGatingEngine {
9
+ stagedPlans = new Map();
10
+ consumedApprovals = new Set();
11
+ stageResponse(options) {
12
+ const { requestContext } = options;
13
+ const nowTime = options.now ? new Date(options.now).getTime() : Date.now();
14
+ const ttlMs = options.ttlMs ?? 60_000;
15
+ const expiresAt = new Date(nowTime + ttlMs).toISOString();
16
+ const evidenceRecords = options.evidenceRecords ?? [];
17
+ const evidenceIds = evidenceRecords.map((e) => e.evidenceId);
18
+ // Calculate aggregate confidence from evidence records if present
19
+ let confidenceSummary = 1.0;
20
+ let uncertaintySummary;
21
+ if (evidenceRecords.length > 0) {
22
+ const confidences = evidenceRecords
23
+ .map((e) => e.confidence)
24
+ .filter((c) => typeof c === 'number' && !isNaN(c));
25
+ if (confidences.length > 0) {
26
+ confidenceSummary = confidences.reduce((sum, c) => sum + c, 0) / confidences.length;
27
+ }
28
+ const uncertainties = evidenceRecords
29
+ .map((e) => e.uncertainty)
30
+ .filter((u) => typeof u === 'string' && u.trim() !== '');
31
+ if (uncertainties.length > 0) {
32
+ uncertaintySummary = uncertainties.join('; ');
33
+ }
34
+ }
35
+ const requiresApproval = options.requiresApproval !== undefined
36
+ ? options.requiresApproval
37
+ : evidenceRecords.some((e) => e.origin === 'ocr' || e.trust === 'untrusted');
38
+ const staged = {
39
+ responseId: generateId('resp'),
40
+ companionId: requestContext.companionId,
41
+ correlationId: requestContext.conversation.correlationId,
42
+ channel: requestContext.conversation?.channel,
43
+ speech: options.candidateSpeech,
44
+ language: options.candidateLanguage,
45
+ evidenceIds,
46
+ citations: options.citations ?? [],
47
+ confidenceSummary,
48
+ uncertaintySummary,
49
+ requiresApproval,
50
+ status: 'STAGED',
51
+ createdAt: new Date(nowTime).toISOString(),
52
+ expiresAt,
53
+ memoryProposals: options.memoryProposals,
54
+ behaviorProposals: options.behaviorProposals,
55
+ internalMonologue: options.internalMonologue,
56
+ };
57
+ this.stagedPlans.set(staged.responseId, staged);
58
+ return staged;
59
+ }
60
+ evaluateGate(staged, allEvidence = [], now = new Date()) {
61
+ const nowTime = new Date(now).getTime();
62
+ // 1. Check if empty speech
63
+ if (!staged.speech || staged.speech.trim() === '') {
64
+ return {
65
+ admissible: false,
66
+ disposition: 'REJECTED',
67
+ reasonCode: 'EMPTY_SPEECH',
68
+ stagedPlan: staged,
69
+ filteredEvidenceIds: [],
70
+ filteredCitations: [],
71
+ diagnostics: { detail: 'Speech content is empty' },
72
+ };
73
+ }
74
+ // 2. Check if expired
75
+ if (staged.expiresAt && new Date(staged.expiresAt).getTime() <= nowTime) {
76
+ staged.status = 'EXPIRED';
77
+ return {
78
+ admissible: false,
79
+ disposition: 'EXPIRED',
80
+ reasonCode: 'EVIDENCE_EXPIRED',
81
+ stagedPlan: staged,
82
+ filteredEvidenceIds: [],
83
+ filteredCitations: [],
84
+ diagnostics: { detail: 'Staged response plan expired' },
85
+ };
86
+ }
87
+ // 3. Disclosure filter on attached evidence
88
+ const attachedEvidence = allEvidence.filter((e) => staged.evidenceIds.includes(e.evidenceId));
89
+ const { admitted, excluded } = (0, evidence_1.filterEvidenceRecords)(attachedEvidence, {
90
+ companionId: staged.companionId,
91
+ channel: staged.channel,
92
+ now,
93
+ });
94
+ // If any evidence attached to this plan violated disclosure in this channel, exclude it
95
+ const admittedEvidenceIds = admitted.map((e) => e.evidenceId);
96
+ const filteredCitations = staged.citations.filter((c) => admitted.some((e) => (c.evidenceId && e.evidenceId === c.evidenceId) ||
97
+ e.sourceId === c.sourceId ||
98
+ (e.documentId && e.documentId === c.documentId)));
99
+ // 4. Explicitly rejected or status check
100
+ if (staged.status === 'REJECTED') {
101
+ return {
102
+ admissible: false,
103
+ disposition: 'REJECTED',
104
+ reasonCode: 'EXPLICITLY_REJECTED',
105
+ stagedPlan: staged,
106
+ filteredEvidenceIds: admittedEvidenceIds,
107
+ filteredCitations,
108
+ };
109
+ }
110
+ // 5. Staged approval check
111
+ if (staged.requiresApproval && staged.status !== 'APPROVED') {
112
+ return {
113
+ admissible: false,
114
+ disposition: staged.status,
115
+ reasonCode: 'APPROVAL_REQUIRED',
116
+ stagedPlan: staged,
117
+ filteredEvidenceIds: admittedEvidenceIds,
118
+ filteredCitations,
119
+ diagnostics: {
120
+ detail: 'Response plan requires approval before external emission',
121
+ excludedEvidenceCount: String(excluded.length),
122
+ },
123
+ };
124
+ }
125
+ // 6. Direct approval / Admissible
126
+ return {
127
+ admissible: true,
128
+ disposition: staged.status === 'APPROVED' ? 'APPROVED' : 'APPROVED',
129
+ reasonCode: 'APPROVED_DIRECT',
130
+ stagedPlan: staged,
131
+ filteredEvidenceIds: admittedEvidenceIds,
132
+ filteredCitations,
133
+ };
134
+ }
135
+ approveResponse(options) {
136
+ const plan = this.stagedPlans.get(options.responseId);
137
+ if (!plan) {
138
+ return { success: false, reason: 'UNKNOWN_APPROVAL_ID' };
139
+ }
140
+ if (this.consumedApprovals.has(options.responseId) || plan.status === 'APPROVED') {
141
+ return { success: false, reason: 'APPROVAL_ALREADY_CONSUMED' };
142
+ }
143
+ if (plan.companionId !== options.companionId) {
144
+ return { success: false, reason: 'COMPANION_MISMATCH' };
145
+ }
146
+ if (plan.correlationId !== options.correlationId) {
147
+ return { success: false, reason: 'APPROVAL_ID_MISMATCH' };
148
+ }
149
+ if (plan.status === 'EXPIRED') {
150
+ return { success: false, reason: 'EVIDENCE_EXPIRED' };
151
+ }
152
+ if (plan.status === 'REJECTED') {
153
+ return { success: false, reason: 'EXPLICITLY_REJECTED' };
154
+ }
155
+ plan.status = 'APPROVED';
156
+ this.consumedApprovals.add(options.responseId);
157
+ return { success: true, plan };
158
+ }
159
+ rejectResponse(options) {
160
+ const plan = this.stagedPlans.get(options.responseId);
161
+ if (!plan) {
162
+ return { success: false, reason: 'UNKNOWN_APPROVAL_ID' };
163
+ }
164
+ if (plan.companionId !== options.companionId) {
165
+ return { success: false, reason: 'COMPANION_MISMATCH' };
166
+ }
167
+ if (plan.correlationId !== options.correlationId) {
168
+ return { success: false, reason: 'APPROVAL_ID_MISMATCH' };
169
+ }
170
+ plan.status = 'REJECTED';
171
+ return { success: true, plan };
172
+ }
173
+ getStagedPlan(responseId) {
174
+ return this.stagedPlans.get(responseId);
175
+ }
176
+ findStagedPlanByCorrelation(companionId, correlationId) {
177
+ for (const plan of this.stagedPlans.values()) {
178
+ if (plan.companionId === companionId && plan.correlationId === correlationId) {
179
+ return plan;
180
+ }
181
+ }
182
+ return undefined;
183
+ }
184
+ }
185
+ exports.ResponseGatingEngine = ResponseGatingEngine;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,186 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const gating_1 = require("./gating");
4
+ describe('T4 Response Gating & Staged Approval Suite', () => {
5
+ let engine;
6
+ const validPublicContext = {
7
+ companionId: 'companion-a',
8
+ actor: {
9
+ actorId: 'actor-a',
10
+ sessionId: 'session-a',
11
+ authorizationRole: 'viewer',
12
+ capabilities: ['chat:public'],
13
+ authenticated: false,
14
+ },
15
+ conversation: {
16
+ channel: 'public',
17
+ correlationId: 'corr-gate-1',
18
+ },
19
+ };
20
+ beforeEach(() => {
21
+ engine = new gating_1.ResponseGatingEngine();
22
+ });
23
+ test('valid grounded response without special approval requirement is approved/admissible directly', () => {
24
+ const evidence = {
25
+ evidenceId: 'ev-pub-1',
26
+ sourceId: 'src-wiki',
27
+ origin: 'knowledge',
28
+ trust: 'configured',
29
+ sensitivity: 'public',
30
+ companionId: 'companion-a',
31
+ correlationId: 'corr-gate-1',
32
+ createdAt: new Date().toISOString(),
33
+ };
34
+ const staged = engine.stageResponse({
35
+ requestContext: validPublicContext,
36
+ candidateSpeech: 'Here is grounded public knowledge.',
37
+ candidateLanguage: 'en',
38
+ evidenceRecords: [evidence],
39
+ citations: [{ sourceId: 'src-wiki', revision: 'r1' }],
40
+ });
41
+ expect(staged.requiresApproval).toBe(false);
42
+ expect(staged.status).toBe('STAGED');
43
+ const evaluation = engine.evaluateGate(staged, [evidence]);
44
+ expect(evaluation.admissible).toBe(true);
45
+ expect(evaluation.disposition).toBe('APPROVED');
46
+ expect(evaluation.reasonCode).toBe('APPROVED_DIRECT');
47
+ expect(evaluation.filteredEvidenceIds).toEqual(['ev-pub-1']);
48
+ expect(evaluation.filteredCitations.length).toBe(1);
49
+ });
50
+ test('response containing untrusted OCR evidence requires approval and remains staged until approved', () => {
51
+ const ocrEvidence = {
52
+ evidenceId: 'ev-ocr-1',
53
+ sourceId: 'vision-ocr',
54
+ origin: 'ocr',
55
+ trust: 'untrusted',
56
+ sensitivity: 'public',
57
+ companionId: 'companion-a',
58
+ correlationId: 'corr-gate-2',
59
+ createdAt: new Date().toISOString(),
60
+ uncertainty: 'OCR detected prompt injection text',
61
+ };
62
+ const staged = engine.stageResponse({
63
+ requestContext: {
64
+ ...validPublicContext,
65
+ conversation: { ...validPublicContext.conversation, correlationId: 'corr-gate-2' },
66
+ },
67
+ candidateSpeech: 'Text extracted from image.',
68
+ candidateLanguage: 'en',
69
+ evidenceRecords: [ocrEvidence],
70
+ });
71
+ expect(staged.requiresApproval).toBe(true);
72
+ expect(staged.status).toBe('STAGED');
73
+ // Before approval -> gating holds it
74
+ const beforeApproval = engine.evaluateGate(staged, [ocrEvidence]);
75
+ expect(beforeApproval.admissible).toBe(false);
76
+ expect(beforeApproval.disposition).toBe('STAGED');
77
+ expect(beforeApproval.reasonCode).toBe('APPROVAL_REQUIRED');
78
+ // Operator approves the response
79
+ const approveResult = engine.approveResponse({
80
+ responseId: staged.responseId,
81
+ companionId: 'companion-a',
82
+ correlationId: 'corr-gate-2',
83
+ });
84
+ expect(approveResult.success).toBe(true);
85
+ // After approval -> gating allows it
86
+ const afterApproval = engine.evaluateGate(staged, [ocrEvidence]);
87
+ expect(afterApproval.admissible).toBe(true);
88
+ expect(afterApproval.disposition).toBe('APPROVED');
89
+ expect(afterApproval.reasonCode).toBe('APPROVED_DIRECT');
90
+ });
91
+ test('unknown or mismatched approval ID is rejected', () => {
92
+ const staged = engine.stageResponse({
93
+ requestContext: validPublicContext,
94
+ candidateSpeech: 'Requires approval',
95
+ candidateLanguage: 'en',
96
+ requiresApproval: true,
97
+ });
98
+ // Unknown response ID
99
+ const unknownRes = engine.approveResponse({
100
+ responseId: 'non-existent-resp',
101
+ companionId: 'companion-a',
102
+ correlationId: 'corr-gate-1',
103
+ });
104
+ expect(unknownRes.success).toBe(false);
105
+ expect(unknownRes.reason).toBe('UNKNOWN_APPROVAL_ID');
106
+ // Companion mismatch
107
+ const companionMismatch = engine.approveResponse({
108
+ responseId: staged.responseId,
109
+ companionId: 'companion-other',
110
+ correlationId: 'corr-gate-1',
111
+ });
112
+ expect(companionMismatch.success).toBe(false);
113
+ expect(companionMismatch.reason).toBe('COMPANION_MISMATCH');
114
+ // Correlation ID mismatch
115
+ const correlationMismatch = engine.approveResponse({
116
+ responseId: staged.responseId,
117
+ companionId: 'companion-a',
118
+ correlationId: 'corr-mismatch',
119
+ });
120
+ expect(correlationMismatch.success).toBe(false);
121
+ expect(correlationMismatch.reason).toBe('APPROVAL_ID_MISMATCH');
122
+ });
123
+ test('rejection prevents response from ever reaching emission', () => {
124
+ const staged = engine.stageResponse({
125
+ requestContext: validPublicContext,
126
+ candidateSpeech: 'Potentially unsafe response',
127
+ candidateLanguage: 'en',
128
+ requiresApproval: true,
129
+ });
130
+ const rejectRes = engine.rejectResponse({
131
+ responseId: staged.responseId,
132
+ companionId: 'companion-a',
133
+ correlationId: 'corr-gate-1',
134
+ });
135
+ expect(rejectRes.success).toBe(true);
136
+ const evalRes = engine.evaluateGate(staged);
137
+ expect(evalRes.admissible).toBe(false);
138
+ expect(evalRes.disposition).toBe('REJECTED');
139
+ expect(evalRes.reasonCode).toBe('EXPLICITLY_REJECTED');
140
+ });
141
+ test('expired staged response plan cannot be approved or emitted', () => {
142
+ const staged = engine.stageResponse({
143
+ requestContext: validPublicContext,
144
+ candidateSpeech: 'Expired response',
145
+ candidateLanguage: 'en',
146
+ requiresApproval: true,
147
+ ttlMs: 100,
148
+ now: new Date(Date.now() - 500),
149
+ });
150
+ const evalRes = engine.evaluateGate(staged, [], new Date());
151
+ expect(evalRes.admissible).toBe(false);
152
+ expect(evalRes.disposition).toBe('EXPIRED');
153
+ expect(evalRes.reasonCode).toBe('EVIDENCE_EXPIRED');
154
+ const approveRes = engine.approveResponse({
155
+ responseId: staged.responseId,
156
+ companionId: 'companion-a',
157
+ correlationId: 'corr-gate-1',
158
+ });
159
+ expect(approveRes.success).toBe(false);
160
+ expect(approveRes.reason).toBe('EVIDENCE_EXPIRED');
161
+ });
162
+ test('foreign companion evidence is filtered out and absent from citations/evidence list', () => {
163
+ const foreignEvidence = {
164
+ evidenceId: 'ev-foreign-1',
165
+ sourceId: 'src-secret',
166
+ origin: 'knowledge',
167
+ trust: 'configured',
168
+ sensitivity: 'private',
169
+ companionId: 'companion-b',
170
+ correlationId: 'corr-gate-1',
171
+ createdAt: new Date().toISOString(),
172
+ };
173
+ const staged = engine.stageResponse({
174
+ requestContext: validPublicContext, // companion-a
175
+ candidateSpeech: 'Response text',
176
+ candidateLanguage: 'en',
177
+ evidenceRecords: [foreignEvidence],
178
+ citations: [{ sourceId: 'src-secret' }],
179
+ });
180
+ const evalRes = engine.evaluateGate(staged, [foreignEvidence]);
181
+ expect(evalRes.admissible).toBe(true);
182
+ // Foreign companion evidence and its citation must be stripped due to companion isolation
183
+ expect(evalRes.filteredEvidenceIds).toEqual([]);
184
+ expect(evalRes.filteredCitations).toEqual([]);
185
+ });
186
+ });