@dreamforgestudiollc/emet 0.2.4 → 0.3.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.
- package/.env.example +63 -0
- package/CHANGELOG.md +84 -3
- package/CHARTER.md +19 -7
- package/README.md +130 -21
- package/areas/emet.md +18 -0
- package/areas/garden.md +18 -0
- package/areas/health.md +18 -0
- package/areas/home.md +18 -0
- package/areas/learning.md +18 -0
- package/areas/state.md +18 -0
- package/docs/AUTHORSHIP.md +3 -3
- package/docs/BOTS.md +4 -0
- package/docs/COVERAGE.md +2 -2
- package/docs/DEPLOY.md +41 -5
- package/docs/ERROR-CODES-SPEC.md +43 -0
- package/docs/ERROR-CODES.md +332 -0
- package/docs/GUARDRAILS-AND-MONORAILS.md +2 -1
- package/docs/GUIDED-SETUP.md +24 -3
- package/docs/PERMISSIONS.md +13 -7
- package/docs/ROADMAP.md +18 -15
- package/docs/SETUP.md +123 -14
- package/docs/SUBKEYS.md +59 -0
- package/gems/artifact-index.json +12 -0
- package/gems/bot-team-backup/floor.json +15 -0
- package/gems/bot-team-backup/gem.json +43 -0
- package/gems/bot-team-backup/guides/BOT_TEAM_BACKUP.md +27 -0
- package/gems/bot-team-backup/guides/BOT_TEAM_RECOVERY.md +23 -0
- package/gems/fieldnote/floor.json +14 -0
- package/gems/fieldnote/gem.json +70 -0
- package/gems/fieldnote/runes/fieldnote.js +4 -0
- package/gems/lean-six-sigma/CHANGELOG.md +10 -0
- package/gems/lean-six-sigma/README.md +92 -0
- package/gems/lean-six-sigma/floor.json +31 -0
- package/gems/lean-six-sigma/gem.json +1296 -0
- package/gems/lean-six-sigma/guides/ASSUMPTIONS.md +45 -0
- package/gems/lean-six-sigma/guides/BELTS.md +52 -0
- package/gems/lean-six-sigma/guides/DMADV.md +56 -0
- package/gems/lean-six-sigma/guides/DMAIC.md +127 -0
- package/gems/lean-six-sigma/guides/FORMULAS.md +330 -0
- package/gems/lean-six-sigma/guides/LEAN.md +97 -0
- package/gems/lean-six-sigma/guides/TEMPLATES.md +279 -0
- package/gems/lean-six-sigma/runes/lss_capability.js +132 -0
- package/gems/lean-six-sigma/runes/lss_control_limits.js +240 -0
- package/gems/lean-six-sigma/runes/lss_dpmo_sigma.js +81 -0
- package/gems/lean-six-sigma/runes/lss_hypothesis.js +298 -0
- package/gems/lean-six-sigma/runes/lss_sample_size.js +81 -0
- package/gems/neurendipity/floor.json +65 -0
- package/gems/neurendipity/gem.json +42 -0
- package/gems/neurendipity/guides/AUTISTIC_BURNOUT.md +81 -0
- package/{guides → gems/neurendipity/guides}/NEURODIVERGENT_SUPPORT.md +17 -8
- package/guides/README.md +3 -0
- package/package.json +12 -5
- package/server.json +48 -4
- package/src/aleph.js +18 -12
- package/src/annotations.js +45 -5
- package/src/atlas-role.js +9 -4
- package/src/attribution.js +555 -0
- package/src/conformance.js +7 -5
- package/src/database.js +34 -17
- package/src/dispatch.js +136 -16
- package/src/env.js +54 -9
- package/src/error-codes.js +394 -0
- package/src/error-log.js +273 -0
- package/src/error-report.js +245 -0
- package/src/floor.js +84 -41
- package/src/gaps.js +41 -8
- package/src/gem-check.js +1360 -0
- package/src/guides.js +31 -4
- package/src/host-reach.js +23 -0
- package/src/http-remote.js +47 -2
- package/src/index.js +10 -2
- package/src/invites.js +6 -5
- package/src/layers.js +9 -8
- package/src/lessons-to-checks.js +3 -3
- package/src/logger.js +2 -1
- package/src/mongo-connect.js +50 -2
- package/src/oauth-provider.js +30 -29
- package/src/owner-approvals.js +281 -0
- package/src/pages.js +806 -0
- package/src/persons.js +22 -1
- package/src/provenance.js +10 -10
- package/src/redact.js +10 -4
- package/src/request-log.js +1 -1
- package/src/rune-dispatch.js +360 -0
- package/src/rune-registry.js +71 -0
- package/src/rune-scope.js +42 -0
- package/src/scopes.js +3 -0
- package/src/session-graph.js +15 -12
- package/src/session.js +10 -10
- package/src/setup.js +307 -36
- package/src/socket.js +545 -0
- package/src/startup-pages.js +26 -8
- package/src/startup-payload.js +12 -8
- package/src/subkey-store.js +358 -0
- package/src/subkeys.js +947 -0
- package/src/tools.js +518 -204
- package/src/transcript-session.js +1 -1
- package/src/validation.js +85 -52
- package/src/version.js +1 -1
- package/templates/AREA.md +35 -0
- package/templates/BOARD.md +2 -2
- package/templates/BOTHANDOFF.md +2 -2
- package/templates/CHARACTER.md +1 -1
- package/templates/HANDOFF.md +1 -1
- package/templates/IDENTITY.md +1 -1
- package/templates/INDEX.md +21 -20
- package/templates/INSTALL.md +1 -1
- package/templates/PROCEDURE.md +1 -1
- package/templates/ROSTER.md +2 -2
- package/templates/SEED.md +2 -2
- package/templates/STAGING.md +2 -2
- package/templates/STANDARD.md +5 -5
- package/templates/THREAD.md +1 -1
- package/templates/USER.md +4 -1
- package/verification/load-gate/corpus.json +1765 -0
- package/verification/load-gate/load-gate.mjs +1246 -0
package/src/tools.js
CHANGED
|
@@ -12,9 +12,24 @@
|
|
|
12
12
|
*/
|
|
13
13
|
|
|
14
14
|
import { connectMongo } from './mongo-connect.js';
|
|
15
|
+
import { newCorrelationId, EMET_INT_001, EMET_CODE_RE, lookupEmetCode } from './error-codes.js';
|
|
16
|
+
import { recordError } from './error-log.js';
|
|
15
17
|
import { resolveModulePath } from './module-path.js';
|
|
16
18
|
import { replacedByOf } from './setup.js';
|
|
17
|
-
import { currentActor, writerStamp, boundSourceTag, LOCAL_SUBJECT } from './persons.js';
|
|
19
|
+
import { currentActor, rawActor, writerStamp, boundSourceTag, declaredAttribution, LOCAL_SUBJECT } from './persons.js';
|
|
20
|
+
import { approvedTags, APPROVALS_DOC } from './attribution.js';
|
|
21
|
+
import { sealAttestation, frozenAttestation } from './rune-dispatch.js';
|
|
22
|
+
|
|
23
|
+
/** Approvals record io for attribution.js (server-kept doc, written as emet-server). */
|
|
24
|
+
export const approvalsDeps = {
|
|
25
|
+
readDoc: (id) => readDoc(id),
|
|
26
|
+
// Compare-and-set on the stored version (the second reader 3). mutateApprovals serializes
|
|
27
|
+
// writers in this process; this check catches a writer elsewhere.
|
|
28
|
+
writeDoc: async (id, content, expectedVersion) => {
|
|
29
|
+
// Atomic across processes: writeDoc filters the update on { doc_id, version: expected }.
|
|
30
|
+
return writeDoc(id, content, 'emet-server', null, null, { serverProvision: true, approvalsRecord: true, expectedVersion: expectedVersion ?? null });
|
|
31
|
+
}
|
|
32
|
+
};
|
|
18
33
|
import {
|
|
19
34
|
ValidationError,
|
|
20
35
|
VALID_LAYERS,
|
|
@@ -116,6 +131,7 @@ export class RateLimitError extends Error {
|
|
|
116
131
|
this.name = 'RateLimitError';
|
|
117
132
|
this.retryAfterMs = retryAfterMs;
|
|
118
133
|
this.statusCode = 429;
|
|
134
|
+
this.emetCode = 'EMET-RATE-001';
|
|
119
135
|
}
|
|
120
136
|
}
|
|
121
137
|
|
|
@@ -348,6 +364,18 @@ export function handleError(error, toolName, logger = null) {
|
|
|
348
364
|
}
|
|
349
365
|
|
|
350
366
|
errorResponse.error.tool = toolName;
|
|
367
|
+
const stamped = error && typeof error.emetCode === 'string' && EMET_CODE_RE.test(error.emetCode) && lookupEmetCode(error.emetCode)
|
|
368
|
+
? error.emetCode
|
|
369
|
+
: EMET_INT_001;
|
|
370
|
+
const correlationId = newCorrelationId();
|
|
371
|
+
errorResponse.error.emet_code = stamped;
|
|
372
|
+
errorResponse.error.correlation_id = correlationId;
|
|
373
|
+
void recordError({
|
|
374
|
+
emet_code: stamped,
|
|
375
|
+
class_code: errorResponse.error.code,
|
|
376
|
+
tool: toolName,
|
|
377
|
+
correlation_id: correlationId
|
|
378
|
+
});
|
|
351
379
|
|
|
352
380
|
// Read at call time. Never attach a stack on the HTTP server.
|
|
353
381
|
if (process.env.DEBUG === 'true' && error?.stack && currentActor().transport !== 'http') {
|
|
@@ -449,7 +477,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
449
477
|
// The tier-1 -> tier-2 pointer is pulled out BEFORE metadata validation and
|
|
450
478
|
// stored as top-level columns, not inside metadata. When this was written
|
|
451
479
|
// metadata was a JSON string the store could not filter into; it is a
|
|
452
|
-
// subdocument now, but the pointer stays top-level because it is
|
|
480
|
+
// subdocument now (EMET ref 6), but the pointer stays top-level because it is
|
|
453
481
|
// indexed there and the reverse lookup depends on that index.
|
|
454
482
|
const { derived_from: rawProvenance, ...restMetadata } = metadata || {};
|
|
455
483
|
let provenance = validateProvenance(rawProvenance);
|
|
@@ -495,13 +523,13 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
495
523
|
const keywordLayer = determineLayer(validatedContent, validatedMetadata);
|
|
496
524
|
const targetLayer = validatedLayer || FALLBACK_LAYER;
|
|
497
525
|
// Lesson fields are refused at the door when the reader would never count
|
|
498
|
-
// them (2026-09-29,
|
|
526
|
+
// them (2026-09-29, procedural ref 397): a malformed key, a key off the meta
|
|
499
527
|
// layer, or a disposition that settles nothing. Checked on the caller's
|
|
500
528
|
// metadata as sent, before anything is written.
|
|
501
529
|
{
|
|
502
530
|
const { checkLessonFields } = await import('./lessons-to-checks.js');
|
|
503
531
|
const lessonProblem = checkLessonFields(targetLayer, incoming);
|
|
504
|
-
if (lessonProblem) throw new ValidationError('metadata.lesson', `${lessonProblem} Nothing was written
|
|
532
|
+
if (lessonProblem) throw new ValidationError('metadata.lesson', `${lessonProblem} Nothing was written.`, { code: 'EMET-MEM-005' });
|
|
505
533
|
}
|
|
506
534
|
if (!validatedLayer) {
|
|
507
535
|
warnings.push(
|
|
@@ -530,6 +558,11 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
530
558
|
}
|
|
531
559
|
} else {
|
|
532
560
|
validatedMetadata.source = sourceDecision.tag;
|
|
561
|
+
if (sourceDecision.from === 'declared' || sourceDecision.from === 'auto' || sourceDecision.from === 'subkey') {
|
|
562
|
+
validatedMetadata.source_basis = sourceDecision.from;
|
|
563
|
+
if (sourceDecision.login) validatedMetadata.source_login = sourceDecision.login;
|
|
564
|
+
if (sourceDecision.from === 'subkey' && sourceDecision.key_id) validatedMetadata.key_id = sourceDecision.key_id;
|
|
565
|
+
}
|
|
533
566
|
delete validatedMetadata.source_defaulted;
|
|
534
567
|
if (sourceDecision.tag) delete validatedMetadata.source_missing;
|
|
535
568
|
else validatedMetadata.source_missing = true;
|
|
@@ -555,6 +588,12 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
555
588
|
}
|
|
556
589
|
validatedMetadata.client_id = stamp.client_id;
|
|
557
590
|
}
|
|
591
|
+
await sealAttestation(validatedMetadata, {
|
|
592
|
+
session_id: options && options.session_id,
|
|
593
|
+
inherited: options && options.inheritedAttestation === true,
|
|
594
|
+
db: dbManager && dbManager.db,
|
|
595
|
+
dbManager
|
|
596
|
+
});
|
|
558
597
|
|
|
559
598
|
// A4: importance is a named bucket. The float is the bucket midpoint
|
|
560
599
|
// unless the caller named a degree (low/mid/high) or still sent a number.
|
|
@@ -572,7 +611,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
572
611
|
}
|
|
573
612
|
|
|
574
613
|
// A5: the charter says whether this layer wants a provenance pointer.
|
|
575
|
-
// 2026-09-29 (
|
|
614
|
+
// 2026-09-29 (procedural ref 398): the pointer is STAMPED when the caller names
|
|
576
615
|
// its transcript session, and a layer whose charter REQUIRES provenance
|
|
577
616
|
// (semantic, procedural) REFUSES a write that has no source at all. The
|
|
578
617
|
// transport is stateless, so the server never guesses which host's session
|
|
@@ -584,8 +623,8 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
584
623
|
let provenanceStamped = false;
|
|
585
624
|
if (!provenance && options && options.session_id !== undefined && options.session_id !== null) {
|
|
586
625
|
const sid = typeof options.session_id === 'string' ? options.session_id.trim() : '';
|
|
587
|
-
if (!sid || sid.length > 200) throw new ValidationError('session_id', 'must be the non-empty transcript session id from emet_session_open. Nothing was written.');
|
|
588
|
-
if (typeof dbManager.transcriptPosition !== 'function') throw new ValidationError('session_id', 'this store cannot read transcript positions, so the pointer cannot be stamped - pass derived_from instead. Nothing was written.');
|
|
626
|
+
if (!sid || sid.length > 200) throw new ValidationError('session_id', 'must be the non-empty transcript session id from emet_session_open. Nothing was written.', { code: 'EMET-MEM-006' });
|
|
627
|
+
if (typeof dbManager.transcriptPosition !== 'function') throw new ValidationError('session_id', 'this store cannot read transcript positions, so the pointer cannot be stamped - pass derived_from instead. Nothing was written.', { code: 'EMET-MEM-007' });
|
|
589
628
|
const pos = await dbManager.transcriptPosition(sid);
|
|
590
629
|
const ex = pos.highest + 1;
|
|
591
630
|
provenance = validateProvenance({ session_id: pos.base, exchange_start: ex, exchange_end: ex });
|
|
@@ -596,7 +635,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
596
635
|
throw new ValidationError('derived_from',
|
|
597
636
|
`${targetLayer} entries must carry their source. Pass session_id (your transcript session from ` +
|
|
598
637
|
`emet_session_open - the server stamps the exchange), or derived_from {session_id, exchange_start, ` +
|
|
599
|
-
`exchange_end}, or derived_from {entries: [ids]} for an entry consolidated from other entries. Nothing was written
|
|
638
|
+
`exchange_end}, or derived_from {entries: [ids]} for an entry consolidated from other entries. Nothing was written.`, { code: 'EMET-MEM-008' });
|
|
600
639
|
}
|
|
601
640
|
if (!provenance && provenancePolicy === 'encouraged') {
|
|
602
641
|
validatedMetadata.provenance_missing = true;
|
|
@@ -677,7 +716,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
677
716
|
const importance = validatedMetadata.importance;
|
|
678
717
|
|
|
679
718
|
const columns = provenanceColumns(provenance);
|
|
680
|
-
// 2026-09-05: the digest is computed BEFORE the write and stored
|
|
719
|
+
// EMET ref 12 (2026-09-05): the digest is computed BEFORE the write and stored
|
|
681
720
|
// as a column, not only compared in the read-back receipt. Without it the
|
|
682
721
|
// aleph claim held for exactly one instant - verified at write, never again.
|
|
683
722
|
const contentSha256 = digest(validatedContent);
|
|
@@ -705,7 +744,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
705
744
|
context: validatedMetadata.context || '',
|
|
706
745
|
emotional_intensity: emotionalIntensity,
|
|
707
746
|
importance,
|
|
708
|
-
// 2026-09-05: stored as a real subdocument, not a JSON string.
|
|
747
|
+
// EMET ref 6 (2026-09-05): stored as a real subdocument, not a JSON string.
|
|
709
748
|
// The promoted columns below stay because they are indexed and the vector
|
|
710
749
|
// filter reads them.
|
|
711
750
|
metadata: validatedMetadata,
|
|
@@ -730,13 +769,13 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
730
769
|
chain_sha256: chainSha256
|
|
731
770
|
};
|
|
732
771
|
|
|
733
|
-
// Option A correction back-pointer (
|
|
772
|
+
// Option A correction back-pointer (Alex, 2026-10-02, procedural ref 405 item 4): a new entry may name the
|
|
734
773
|
// entry it partly corrects. The parent must exist in the same layer, and is checked BEFORE the insert so a
|
|
735
774
|
// refused correction writes nothing.
|
|
736
775
|
if (validatedMetadata.corrects !== undefined && validatedMetadata.corrects !== null) {
|
|
737
776
|
const parent = await dbManager.readMemory(targetLayer, validatedMetadata.corrects);
|
|
738
777
|
if (!parent) {
|
|
739
|
-
throw new ValidationError('corrects', `No entry with id ${validatedMetadata.corrects} in layer '${targetLayer}' - a correction names an entry in its own layer. Nothing was written
|
|
778
|
+
throw new ValidationError('corrects', `No entry with id ${validatedMetadata.corrects} in layer '${targetLayer}' - a correction names an entry in its own layer. Nothing was written.`, { code: 'EMET-MEM-009' });
|
|
740
779
|
}
|
|
741
780
|
}
|
|
742
781
|
|
|
@@ -855,7 +894,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
|
|
|
855
894
|
'Failed to save memory',
|
|
856
895
|
'save_memory',
|
|
857
896
|
{ layer: layer || 'auto' }
|
|
858
|
-
);
|
|
897
|
+
, { code: 'EMET-DB-013' });
|
|
859
898
|
}
|
|
860
899
|
}
|
|
861
900
|
|
|
@@ -946,8 +985,8 @@ export async function resolveSupersessionChain(read, entry, maxHops = 50) {
|
|
|
946
985
|
}
|
|
947
986
|
|
|
948
987
|
/**
|
|
949
|
-
* Option A correction back-pointer (
|
|
950
|
-
* second read of
|
|
988
|
+
* Option A correction back-pointer (Alex, 2026-10-02, procedural ref 405 item 4; the reviewer's sketch in his
|
|
989
|
+
* second read of episodic ref 604). Episodic entries are immutable events, so a PARTIAL correction cannot
|
|
951
990
|
* supersede its parent: supersession would put an end date on the whole parent and present every item
|
|
952
991
|
* in it as replaced. Instead the new entry carries metadata.corrects = <parent id>, and the parent is MARKED:
|
|
953
992
|
* its corrected_by array gains the new id. The parent's content, digest and is_live are untouched; its
|
|
@@ -1030,48 +1069,53 @@ export async function reviseMemory(dbManager, layer, target_id, content, metadat
|
|
|
1030
1069
|
// Which layers may be revised is the charter's call (layers.js), not a
|
|
1031
1070
|
// string comparison here. Today only episodic says false.
|
|
1032
1071
|
if (policyFor(validatedLayer).revisable === false) {
|
|
1033
|
-
throw new ValidationError('layer', 'Episodic revision is prohibited - events are immutable history. Save a new episodic entry instead.');
|
|
1072
|
+
throw new ValidationError('layer', 'Episodic revision is prohibited - events are immutable history. Save a new episodic entry instead.', { code: 'EMET-MEM-010' });
|
|
1034
1073
|
}
|
|
1035
1074
|
const targetId = Number(target_id);
|
|
1036
1075
|
if (!Number.isFinite(targetId) || !Number.isInteger(targetId) || targetId <= 0) {
|
|
1037
|
-
throw new ValidationError('target_id', 'target_id must be a positive integer');
|
|
1076
|
+
throw new ValidationError('target_id', 'target_id must be a positive integer', { code: 'EMET-MEM-011' });
|
|
1038
1077
|
}
|
|
1039
1078
|
const validatedContent = validateContent(content);
|
|
1040
1079
|
// A7: metadata is validated exactly ONCE, inside saveMemory, with
|
|
1041
1080
|
// `supersedes` already present as a first-class field. Validating here and
|
|
1042
1081
|
// again there is what used to relocate it under custom on the second pass.
|
|
1043
1082
|
if (metadata !== null && metadata !== undefined && !isPlainObject(metadata)) {
|
|
1044
|
-
throw new ValidationError('metadata', 'Metadata must be an object', typeof metadata);
|
|
1083
|
+
throw new ValidationError('metadata', 'Metadata must be an object', typeof metadata, { code: 'EMET-VAL-018' });
|
|
1045
1084
|
}
|
|
1046
|
-
// 2026-09-29 (a decision record): a revision with no source of its own cites
|
|
1047
|
-
// the entry it revises, so revising a semantic or procedural entry is never
|
|
1048
|
-
// refused for want of a pointer. A caller-supplied derived_from wins.
|
|
1049
|
-
const revisionMetadata = {
|
|
1050
|
-
...(metadata || {}),
|
|
1051
|
-
supersedes: targetId,
|
|
1052
|
-
...((metadata && metadata.derived_from) ? {} : { derived_from: { entries: [targetId] } })
|
|
1053
|
-
};
|
|
1054
|
-
|
|
1055
1085
|
await dbManager.getConnection(validatedLayer);
|
|
1056
1086
|
const col = dbManager.collectionFor(validatedLayer);
|
|
1057
1087
|
|
|
1058
1088
|
const target = await col.findOne({ id: targetId });
|
|
1059
1089
|
if (!target) {
|
|
1060
|
-
throw new ValidationError('target_id', `No entry with id ${targetId} in layer '${validatedLayer}'
|
|
1090
|
+
throw new ValidationError('target_id', `No entry with id ${targetId} in layer '${validatedLayer}'`, { code: 'EMET-MEM-012' });
|
|
1061
1091
|
}
|
|
1062
1092
|
const targetMd = parseMetadata(target.metadata);
|
|
1063
1093
|
if (isMemorySuperseded(targetMd)) {
|
|
1064
|
-
throw new ValidationError('target_id', `Entry ${targetId} is already superseded by ${targetMd.superseded_by} - revise the CURRENT entry, not the archived one
|
|
1094
|
+
throw new ValidationError('target_id', `Entry ${targetId} is already superseded by ${targetMd.superseded_by} - revise the CURRENT entry, not the archived one`, { code: 'EMET-MEM-013' });
|
|
1065
1095
|
}
|
|
1096
|
+
// 2026-09-29 (procedural ref 398): a revision with no source of its own cites
|
|
1097
|
+
// the entry it revises, so revising a semantic or procedural entry is never
|
|
1098
|
+
// refused for want of a pointer. A caller-supplied derived_from wins.
|
|
1099
|
+
// Attestation copied from the parent wins over a caller value. A different
|
|
1100
|
+
// value was already refused.
|
|
1101
|
+
const priorAttestation = frozenAttestation(targetMd, metadata);
|
|
1102
|
+
const revisionMetadata = {
|
|
1103
|
+
...(metadata || {}),
|
|
1104
|
+
...(priorAttestation || {}),
|
|
1105
|
+
supersedes: targetId,
|
|
1106
|
+
...((metadata && metadata.derived_from) ? {} : { derived_from: { entries: [targetId] } })
|
|
1107
|
+
};
|
|
1066
1108
|
|
|
1067
|
-
const saved = await saveMemory(dbManager, validatedContent, validatedLayer, revisionMetadata, logger, null
|
|
1109
|
+
const saved = await saveMemory(dbManager, validatedContent, validatedLayer, revisionMetadata, logger, null, {
|
|
1110
|
+
inheritedAttestation: Boolean(priorAttestation)
|
|
1111
|
+
});
|
|
1068
1112
|
|
|
1069
1113
|
targetMd.superseded_by = saved.id;
|
|
1070
1114
|
targetMd.superseded_at = saved.timestamp;
|
|
1071
1115
|
// Write BOTH the metadata copy and the promoted top-level column. The
|
|
1072
1116
|
// top-level one is what a reader follows (indexed); the metadata copy
|
|
1073
1117
|
// stays for audit. Always written as a subdocument - a parent still
|
|
1074
|
-
// carrying the legacy string shape is converted by this touch.
|
|
1118
|
+
// carrying the legacy string shape is converted by this touch (EMET ref 6).
|
|
1075
1119
|
// is_live is left as it was. Supersession is the end date and the link
|
|
1076
1120
|
// to the new entry, not a flag that hides the old one.
|
|
1077
1121
|
await col.updateOne({ id: targetId }, { $set: {
|
|
@@ -1112,7 +1156,7 @@ export async function reviseMemory(dbManager, layer, target_id, content, metadat
|
|
|
1112
1156
|
};
|
|
1113
1157
|
} catch (error) {
|
|
1114
1158
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
1115
|
-
throw new DatabaseError(`Failed to revise memory: ${error.message}`, 'revise_memory');
|
|
1159
|
+
throw new DatabaseError(`Failed to revise memory: ${error.message}`, 'revise_memory', { code: 'EMET-DB-014' });
|
|
1116
1160
|
}
|
|
1117
1161
|
}
|
|
1118
1162
|
|
|
@@ -1360,19 +1404,19 @@ export async function recallMemories(dbManager, query, layer = null, limit = 10,
|
|
|
1360
1404
|
|
|
1361
1405
|
try {
|
|
1362
1406
|
if (query === null || query === undefined || (typeof query === 'string' && query.trim() === '')) {
|
|
1363
|
-
throw new ValidationError('query', 'Query is required');
|
|
1407
|
+
throw new ValidationError('query', 'Query is required', { code: 'EMET-VAL-005' });
|
|
1364
1408
|
}
|
|
1365
1409
|
if (typeof query !== 'string') {
|
|
1366
|
-
throw new ValidationError('query', 'Query must be a string');
|
|
1410
|
+
throw new ValidationError('query', 'Query must be a string', { code: 'EMET-VAL-006' });
|
|
1367
1411
|
}
|
|
1368
1412
|
if (query.length > CONTENT_LIMITS.MAX_QUERY_LENGTH) {
|
|
1369
|
-
throw new ValidationError('query', `Query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH} characters
|
|
1413
|
+
throw new ValidationError('query', `Query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH} characters`, { code: 'EMET-VAL-008' });
|
|
1370
1414
|
}
|
|
1371
1415
|
const validatedQuery = query.trim();
|
|
1372
1416
|
const validatedLayer = layer ? validateLayer(layer) : null;
|
|
1373
1417
|
const validatedLimit = validateLimit(limit);
|
|
1374
1418
|
if (options && options.order != null && options.order !== 'latest') {
|
|
1375
|
-
throw new ValidationError('order', "order must be 'latest' when it is set");
|
|
1419
|
+
throw new ValidationError('order', "order must be 'latest' when it is set", { code: 'EMET-MEM-014' });
|
|
1376
1420
|
}
|
|
1377
1421
|
|
|
1378
1422
|
logger?.debug('Recalling memories', {
|
|
@@ -1488,7 +1532,7 @@ export async function recallMemories(dbManager, query, layer = null, limit = 10,
|
|
|
1488
1532
|
'Failed to recall memories',
|
|
1489
1533
|
'recall_memories',
|
|
1490
1534
|
{ layer: layer || 'all' }
|
|
1491
|
-
);
|
|
1535
|
+
, { code: 'EMET-DB-015' });
|
|
1492
1536
|
}
|
|
1493
1537
|
}
|
|
1494
1538
|
|
|
@@ -1543,7 +1587,7 @@ export async function queryLayer(dbManager, layer, options = {}, logger = null,
|
|
|
1543
1587
|
const searchTerm = validatedOptions.params[0];
|
|
1544
1588
|
if (typeof searchTerm === 'string') {
|
|
1545
1589
|
if (searchTerm.length > CONTENT_LIMITS.MAX_QUERY_LENGTH) {
|
|
1546
|
-
throw new ValidationError('params[0]', `Search term exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}
|
|
1590
|
+
throw new ValidationError('params[0]', `Search term exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`, { code: 'EMET-MEM-015' });
|
|
1547
1591
|
}
|
|
1548
1592
|
filter = { $or: [{ content: containsRegex(searchTerm) }, { context: containsRegex(searchTerm) }] };
|
|
1549
1593
|
}
|
|
@@ -1626,7 +1670,7 @@ export async function queryLayer(dbManager, layer, options = {}, logger = null,
|
|
|
1626
1670
|
// there is not even one to read - that transport's logger discards warn().
|
|
1627
1671
|
// So the ignored keys ride back in the response envelope, where the person
|
|
1628
1672
|
// who wrote the bad filter will actually see them. This is the surface that
|
|
1629
|
-
// would have caught the 2026-09-08 phantom defect as it happened.
|
|
1673
|
+
// would have caught the 2026-09-08 phantom defect as it happened (ref 259).
|
|
1630
1674
|
if (validatedOptions._unknown_filter_keys) {
|
|
1631
1675
|
attachWarnings(results, [
|
|
1632
1676
|
`Ignored unrecognised filter key(s): ${validatedOptions._unknown_filter_keys.join(', ')}. `
|
|
@@ -1665,7 +1709,7 @@ export async function queryLayer(dbManager, layer, options = {}, logger = null,
|
|
|
1665
1709
|
'Failed to query layer',
|
|
1666
1710
|
'query_layer',
|
|
1667
1711
|
{ layer: layer || 'unknown' }
|
|
1668
|
-
);
|
|
1712
|
+
, { code: 'EMET-DB-016' });
|
|
1669
1713
|
}
|
|
1670
1714
|
}
|
|
1671
1715
|
|
|
@@ -1714,7 +1758,7 @@ export async function getStatus(dbManager, logger = null) {
|
|
|
1714
1758
|
throw new DatabaseError(
|
|
1715
1759
|
'Failed to get system status',
|
|
1716
1760
|
'emet_status'
|
|
1717
|
-
);
|
|
1761
|
+
, { code: 'EMET-DB-017' });
|
|
1718
1762
|
}
|
|
1719
1763
|
}
|
|
1720
1764
|
|
|
@@ -1737,14 +1781,14 @@ export async function queryTranscripts(timestamp_start, timestamp_end, session_i
|
|
|
1737
1781
|
const startTime = Date.now();
|
|
1738
1782
|
try {
|
|
1739
1783
|
if (typeof timestamp_start !== 'number' || typeof timestamp_end !== 'number')
|
|
1740
|
-
throw new ValidationError('timestamp_start and timestamp_end must be numbers (Unix timestamps)');
|
|
1784
|
+
throw new ValidationError('timestamp_start and timestamp_end must be numbers (Unix timestamps)', { code: 'EMET-SESS-002' });
|
|
1741
1785
|
if (timestamp_start >= timestamp_end)
|
|
1742
|
-
throw new ValidationError('timestamp_start must be less than timestamp_end');
|
|
1786
|
+
throw new ValidationError('timestamp_start must be less than timestamp_end', { code: 'EMET-SESS-003' });
|
|
1743
1787
|
// Security audit 2026-09-29: session_id reached the query unchecked, so an
|
|
1744
1788
|
// object such as {"$ne": null} was an operator, not an id. Every other
|
|
1745
1789
|
// doc_id / session_id door already refused a non-string.
|
|
1746
1790
|
if (session_id !== null && session_id !== undefined && typeof session_id !== 'string')
|
|
1747
|
-
throw new ValidationError('session_id', 'must be a string');
|
|
1791
|
+
throw new ValidationError('session_id', 'must be a string', { code: 'EMET-SESS-004' });
|
|
1748
1792
|
const effectiveLimit = Math.min(Math.max(1, limit || 50), 500);
|
|
1749
1793
|
const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 5000, maxPoolSize: 10 });
|
|
1750
1794
|
const db = client.db(MONGODB_DB);
|
|
@@ -1778,7 +1822,7 @@ export async function queryTranscripts(timestamp_start, timestamp_end, session_i
|
|
|
1778
1822
|
};
|
|
1779
1823
|
} catch (error) {
|
|
1780
1824
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
1781
|
-
throw new DatabaseError(`Failed to query transcripts: ${error.message}`, 'query_transcripts');
|
|
1825
|
+
throw new DatabaseError(`Failed to query transcripts: ${error.message}`, 'query_transcripts', { code: 'EMET-DB-018' });
|
|
1782
1826
|
}
|
|
1783
1827
|
}
|
|
1784
1828
|
|
|
@@ -1845,12 +1889,12 @@ export function assertExchangeBudget(parts) {
|
|
|
1845
1889
|
for (const part of parts) {
|
|
1846
1890
|
const text = String(part ?? '');
|
|
1847
1891
|
if (text.length > EXCHANGE_FIELD_MAX) {
|
|
1848
|
-
throw new ValidationError(`an exchange field exceeds ${EXCHANGE_FIELD_MAX} characters. Nothing was written
|
|
1892
|
+
throw new ValidationError(`an exchange field exceeds ${EXCHANGE_FIELD_MAX} characters. Nothing was written.`, { code: 'EMET-TRN-001' });
|
|
1849
1893
|
}
|
|
1850
1894
|
total += text.length;
|
|
1851
1895
|
}
|
|
1852
1896
|
if (total > EXCHANGE_REQUEST_MAX) {
|
|
1853
|
-
throw new ValidationError(`this transcript request exceeds ${EXCHANGE_REQUEST_MAX} characters. Nothing was written
|
|
1897
|
+
throw new ValidationError(`this transcript request exceeds ${EXCHANGE_REQUEST_MAX} characters. Nothing was written.`, { code: 'EMET-TRN-002' });
|
|
1854
1898
|
}
|
|
1855
1899
|
}
|
|
1856
1900
|
|
|
@@ -1866,15 +1910,15 @@ export async function saveTranscript(session_id, session_start, session_end, exc
|
|
|
1866
1910
|
|
|
1867
1911
|
try {
|
|
1868
1912
|
if (!session_id || typeof session_id !== 'string') {
|
|
1869
|
-
throw new ValidationError('session_id must be a non-empty string');
|
|
1913
|
+
throw new ValidationError('session_id must be a non-empty string', { code: 'EMET-TRN-003' });
|
|
1870
1914
|
}
|
|
1871
1915
|
if (typeof session_start !== 'number') {
|
|
1872
|
-
throw new ValidationError('session_start must be a Unix timestamp (number)');
|
|
1916
|
+
throw new ValidationError('session_start must be a Unix timestamp (number)', { code: 'EMET-TRN-004' });
|
|
1873
1917
|
}
|
|
1874
1918
|
|
|
1875
1919
|
const resolvedChannel = channel || 'claude_project';
|
|
1876
1920
|
if (!Array.isArray(exchanges) || exchanges.length === 0) {
|
|
1877
|
-
throw new ValidationError('exchanges must be a non-empty array');
|
|
1921
|
+
throw new ValidationError('exchanges must be a non-empty array', { code: 'EMET-TRN-005' });
|
|
1878
1922
|
}
|
|
1879
1923
|
assertExchangeBudget(exchanges.flatMap((ex) => [ex && ex.user_message, ex && ex.assistant_message]));
|
|
1880
1924
|
const resolvedExchanges = exchanges;
|
|
@@ -1928,7 +1972,7 @@ export async function saveTranscript(session_id, session_start, session_end, exc
|
|
|
1928
1972
|
|
|
1929
1973
|
} catch (error) {
|
|
1930
1974
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
1931
|
-
throw new DatabaseError(`Failed to save session transcript: ${error.message}`, 'save_transcript');
|
|
1975
|
+
throw new DatabaseError(`Failed to save session transcript: ${error.message}`, 'save_transcript', { code: 'EMET-DB-019' });
|
|
1932
1976
|
}
|
|
1933
1977
|
}
|
|
1934
1978
|
|
|
@@ -2021,7 +2065,7 @@ export async function dropsSeenForOpen(load_id) {
|
|
|
2021
2065
|
throw new DatabaseError(
|
|
2022
2066
|
`emet_session_open could not load unhandled drops from the store, so no session was opened: ${e && e.message}. Nothing was stamped.`,
|
|
2023
2067
|
'emet_session_open'
|
|
2024
|
-
);
|
|
2068
|
+
, { code: 'EMET-DB-020' });
|
|
2025
2069
|
}
|
|
2026
2070
|
}
|
|
2027
2071
|
|
|
@@ -2038,9 +2082,9 @@ export async function sessionOpen({ slug, load_id } = {}, logger = null, dbManag
|
|
|
2038
2082
|
try {
|
|
2039
2083
|
resolved = await firstUnclosedBase(requested, (b) => sessionStatus(b, dbManager));
|
|
2040
2084
|
} catch (e) {
|
|
2041
|
-
if (e && e.allClosed) throw new ValidationError('slug', `${e.message} Nothing was opened
|
|
2085
|
+
if (e && e.allClosed) throw new ValidationError('slug', `${e.message} Nothing was opened.`, { code: 'EMET-MEM-016' });
|
|
2042
2086
|
throw new DatabaseError(`emet_session_open could not check whether ${requested} is already closed, so no session was opened: ${e && e.message}. ` +
|
|
2043
|
-
'Call emet_session_open again with the same slug and load_id.', 'emet_session_open');
|
|
2087
|
+
'Call emet_session_open again with the same slug and load_id.', 'emet_session_open', { code: 'EMET-DB-021' });
|
|
2044
2088
|
}
|
|
2045
2089
|
const base = resolved.base;
|
|
2046
2090
|
const session_id = partId(base, 1);
|
|
@@ -2053,6 +2097,7 @@ export async function sessionOpen({ slug, load_id } = {}, logger = null, dbManag
|
|
|
2053
2097
|
: 'Nothing was merged into another session.')
|
|
2054
2098
|
: null;
|
|
2055
2099
|
logger?.info?.('transcript session open', { session_id, ...(suffixed ? { requested } : {}) });
|
|
2100
|
+
const session_handle = await subkeyHandleForOpen(rawActor(), base, now);
|
|
2056
2101
|
// Startup page completion (2026-10-03). Through dispatch, an open with no
|
|
2057
2102
|
// load_id or with pages missing is refused before this runs (the
|
|
2058
2103
|
// startup_pages gate); a direct call is told what was checked.
|
|
@@ -2077,6 +2122,7 @@ export async function sessionOpen({ slug, load_id } = {}, logger = null, dbManag
|
|
|
2077
2122
|
return {
|
|
2078
2123
|
session_id,
|
|
2079
2124
|
base,
|
|
2125
|
+
...(session_handle ? { session_handle } : {}),
|
|
2080
2126
|
drops_seen,
|
|
2081
2127
|
...(drops_unverified ? { drops_unverified: true } : {}),
|
|
2082
2128
|
next_exchange_index: 1,
|
|
@@ -2130,6 +2176,19 @@ export function startupPagesCheck(loadId, logger = null, sessionId = null, now =
|
|
|
2130
2176
|
return { load_id: c.load_id, checked: true, complete: false, of: c.of, served: c.served, missing: c.missing, notice };
|
|
2131
2177
|
}
|
|
2132
2178
|
|
|
2179
|
+
/** The one-time session handle for a sub-key open. Null when this open did not present a key. Never logged. */
|
|
2180
|
+
async function subkeyHandleForOpen(actor, base, now) {
|
|
2181
|
+
if (!actor || setting('SUBKEYS') !== '1') return null;
|
|
2182
|
+
const { takeOpenToken, commitLiveSession } = await import('./subkeys.js');
|
|
2183
|
+
if (!takeOpenToken(actor)) return null;
|
|
2184
|
+
try {
|
|
2185
|
+
return await commitLiveSession(approvalsDeps, actor, base, now);
|
|
2186
|
+
} catch (e) {
|
|
2187
|
+
if (e && e.attributionRefusal) throw new ValidationError('subkey', e.message, { code: 'EMET-AUTH-028' });
|
|
2188
|
+
throw e;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2133
2192
|
export async function transcriptAppend(args = {}, logger = null) {
|
|
2134
2193
|
const session_id = args.session_id;
|
|
2135
2194
|
const user_message = args.user_message;
|
|
@@ -2139,10 +2198,10 @@ export async function transcriptAppend(args = {}, logger = null) {
|
|
|
2139
2198
|
const channel = args.channel;
|
|
2140
2199
|
redactWithReport(String(user_message || '') + String(assistant_message || ''));
|
|
2141
2200
|
if (!session_id || typeof session_id !== 'string') {
|
|
2142
|
-
throw new ValidationError('session_id is required');
|
|
2201
|
+
throw new ValidationError('session_id is required', { code: 'EMET-MEM-017' });
|
|
2143
2202
|
}
|
|
2144
2203
|
if (typeof user_message !== 'string' || typeof assistant_message !== 'string') {
|
|
2145
|
-
throw new ValidationError('user_message and assistant_message must be strings');
|
|
2204
|
+
throw new ValidationError('user_message and assistant_message must be strings', { code: 'EMET-TRN-006' });
|
|
2146
2205
|
}
|
|
2147
2206
|
assertExchangeBudget([user_message, assistant_message]);
|
|
2148
2207
|
const {
|
|
@@ -2181,6 +2240,11 @@ export async function transcriptAppend(args = {}, logger = null) {
|
|
|
2181
2240
|
person_id: stamp.person_id,
|
|
2182
2241
|
client_id: stamp.client_id
|
|
2183
2242
|
};
|
|
2243
|
+
const attr = declaredAttribution();
|
|
2244
|
+
if (attr && attr.basis === 'subkey' && attr.keyId) {
|
|
2245
|
+
row.key_id = attr.keyId;
|
|
2246
|
+
row.source_basis = 'subkey';
|
|
2247
|
+
}
|
|
2184
2248
|
|
|
2185
2249
|
// Build 1 (2026-09-27): the first append of a session must carry the
|
|
2186
2250
|
// measured machine line, or say there is no local shell. The rule lived in
|
|
@@ -2194,7 +2258,7 @@ export async function transcriptAppend(args = {}, logger = null) {
|
|
|
2194
2258
|
const notes = await client.db(MONGODB_DB).collection('documents')
|
|
2195
2259
|
.findOne({ doc_id: installDoc(), retired: { $ne: true } }, { projection: { content: 1 } });
|
|
2196
2260
|
machineCheck = machineLineCheck(assistant_message, knownMachinesFromInstallNotes(notes && notes.content));
|
|
2197
|
-
if (!machineCheck.ok) throw new ValidationError(machineCheck.reason);
|
|
2261
|
+
if (!machineCheck.ok) throw new ValidationError(machineCheck.reason, { code: 'EMET-MEM-018' });
|
|
2198
2262
|
}
|
|
2199
2263
|
|
|
2200
2264
|
if (!live) {
|
|
@@ -2251,11 +2315,11 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
|
|
|
2251
2315
|
const startTime = Date.now();
|
|
2252
2316
|
try {
|
|
2253
2317
|
if (!session_id || typeof session_id !== 'string')
|
|
2254
|
-
throw new ValidationError('session_id must be a non-empty string');
|
|
2318
|
+
throw new ValidationError('session_id must be a non-empty string', { code: 'EMET-TRN-003' });
|
|
2255
2319
|
if (!Array.isArray(exchanges) || exchanges.length === 0)
|
|
2256
|
-
throw new ValidationError('exchanges must be a non-empty array - a revision replaces the whole part, not a field within it');
|
|
2320
|
+
throw new ValidationError('exchanges must be a non-empty array - a revision replaces the whole part, not a field within it', { code: 'EMET-TRN-007' });
|
|
2257
2321
|
if (!reason || typeof reason !== 'string' || reason.trim().length < 10)
|
|
2258
|
-
throw new ValidationError('reason is required and must describe what was wrong - at least 10 characters. An unexplained correction is a silent rewrite.');
|
|
2322
|
+
throw new ValidationError('reason is required and must describe what was wrong - at least 10 characters. An unexplained correction is a silent rewrite.', { code: 'EMET-TRN-008' });
|
|
2259
2323
|
|
|
2260
2324
|
const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 5000, maxPoolSize: 10 });
|
|
2261
2325
|
const db = client.db(MONGODB_DB);
|
|
@@ -2266,7 +2330,7 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
|
|
|
2266
2330
|
|| await col.findOne({ session_id });
|
|
2267
2331
|
if (!parent) {
|
|
2268
2332
|
await client.close();
|
|
2269
|
-
throw new ValidationError(`No transcript found under session_id "${session_id}". Use save_transcript to write a new part; revise_transcript only corrects one that exists
|
|
2333
|
+
throw new ValidationError(`No transcript found under session_id "${session_id}". Use save_transcript to write a new part; revise_transcript only corrects one that exists.`, { code: 'EMET-TRN-009' });
|
|
2270
2334
|
}
|
|
2271
2335
|
|
|
2272
2336
|
const revision = (typeof parent.revision === 'number' ? parent.revision : 1) + 1;
|
|
@@ -2326,7 +2390,7 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
|
|
|
2326
2390
|
};
|
|
2327
2391
|
} catch (error) {
|
|
2328
2392
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
2329
|
-
throw new DatabaseError(`Failed to revise transcript: ${error.message}`, 'revise_transcript');
|
|
2393
|
+
throw new DatabaseError(`Failed to revise transcript: ${error.message}`, 'revise_transcript', { code: 'EMET-DB-022' });
|
|
2330
2394
|
}
|
|
2331
2395
|
}
|
|
2332
2396
|
|
|
@@ -2462,7 +2526,7 @@ export function checkReadPin(doc_id, current, opts = {}) {
|
|
|
2462
2526
|
const hasS = typeof wantS === 'string' && wantS.trim() !== '';
|
|
2463
2527
|
if (!hasV && !hasS) return;
|
|
2464
2528
|
if (hasV && !(Number.isInteger(Number(wantV)) && Number(wantV) >= 1)) {
|
|
2465
|
-
throw new ValidationError('expected_version', 'expected_version is the whole-number `version` an earlier page of this document returned.');
|
|
2529
|
+
throw new ValidationError('expected_version', 'expected_version is the whole-number `version` an earlier page of this document returned.', { code: 'EMET-DOC-004' });
|
|
2466
2530
|
}
|
|
2467
2531
|
const vChanged = hasV && current.version !== undefined && current.version !== null && Number(wantV) !== Number(current.version);
|
|
2468
2532
|
const sChanged = hasS && String(current.sha256 || '').toLowerCase() !== wantS.trim().toLowerCase();
|
|
@@ -2473,12 +2537,12 @@ export function checkReadPin(doc_id, current, opts = {}) {
|
|
|
2473
2537
|
throw new ValidationError('expected_version',
|
|
2474
2538
|
`${doc_id}: document changed - restart from offset 0. You read earlier pages of ${was}; it is now ${now}. ` +
|
|
2475
2539
|
'Pages of two versions are never joined, so nothing was returned. Call read_doc again with offset 0 and no expected_version, ' +
|
|
2476
|
-
'discard the pages you already have, and read every page of the new version.');
|
|
2540
|
+
'discard the pages you already have, and read every page of the new version.', { code: 'EMET-DOC-005' });
|
|
2477
2541
|
}
|
|
2478
2542
|
|
|
2479
2543
|
export async function readDoc(doc_id, logger = null, opts = {}) {
|
|
2480
2544
|
try {
|
|
2481
|
-
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
|
|
2545
|
+
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
|
|
2482
2546
|
const guide = readShippedGuide(doc_id);
|
|
2483
2547
|
if (guide) {
|
|
2484
2548
|
checkReadPin(doc_id, guide, opts);
|
|
@@ -2488,7 +2552,7 @@ export async function readDoc(doc_id, logger = null, opts = {}) {
|
|
|
2488
2552
|
const { client, col } = await _docsClient();
|
|
2489
2553
|
try {
|
|
2490
2554
|
const doc = await col.findOne({ doc_id });
|
|
2491
|
-
if (!doc) throw new ValidationError(`Document not found: ${doc_id}
|
|
2555
|
+
if (!doc) throw new ValidationError(`Document not found: ${doc_id}`, { code: 'EMET-DOC-002' });
|
|
2492
2556
|
checkReadPin(doc_id, doc, opts);
|
|
2493
2557
|
const { content, page } = pageContent(doc.content, opts.offset ?? 0, opts.limit ?? null);
|
|
2494
2558
|
// A retired document is still returned in full - retain and mark, never
|
|
@@ -2497,6 +2561,8 @@ export async function readDoc(doc_id, logger = null, opts = {}) {
|
|
|
2497
2561
|
return { doc_id: doc.doc_id, content, sha256: doc.sha256, version: doc.version,
|
|
2498
2562
|
updated_at: doc.updated_at, updated_by: doc.updated_by || null,
|
|
2499
2563
|
client_id: doc.client_id || null, session_id: doc.session_id || null,
|
|
2564
|
+
...(doc.key_id ? { key_id: doc.key_id } : {}),
|
|
2565
|
+
...(doc.source_basis ? { source_basis: doc.source_basis } : {}),
|
|
2500
2566
|
path_hint: doc.path_hint || null, size: doc.content.length,
|
|
2501
2567
|
size_unit: 'characters', size_bytes: Buffer.byteLength(doc.content, 'utf8'),
|
|
2502
2568
|
...(page ? { page } : {}),
|
|
@@ -2516,7 +2582,7 @@ export async function readDoc(doc_id, logger = null, opts = {}) {
|
|
|
2516
2582
|
} finally { await client.close(); }
|
|
2517
2583
|
} catch (error) {
|
|
2518
2584
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
2519
|
-
throw new DatabaseError(`Failed to read document: ${error.message}`, 'read_doc');
|
|
2585
|
+
throw new DatabaseError(`Failed to read document: ${error.message}`, 'read_doc', { code: 'EMET-DB-023' });
|
|
2520
2586
|
}
|
|
2521
2587
|
}
|
|
2522
2588
|
|
|
@@ -2530,8 +2596,8 @@ export async function readDoc(doc_id, logger = null, opts = {}) {
|
|
|
2530
2596
|
*/
|
|
2531
2597
|
export async function readDocHistory(doc_id, version = null, logger = null) {
|
|
2532
2598
|
try {
|
|
2533
|
-
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
|
|
2534
|
-
if (version !== null && version !== undefined && (!Number.isInteger(version) || version < 1)) throw new ValidationError('version must be a positive integer');
|
|
2599
|
+
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
|
|
2600
|
+
if (version !== null && version !== undefined && (!Number.isInteger(version) || version < 1)) throw new ValidationError('version must be a positive integer', { code: 'EMET-DOC-006' });
|
|
2535
2601
|
const { client, col, hist } = await _docsClient();
|
|
2536
2602
|
try {
|
|
2537
2603
|
const current = await col.findOne({ doc_id });
|
|
@@ -2539,6 +2605,8 @@ export async function readDocHistory(doc_id, version = null, logger = null) {
|
|
|
2539
2605
|
const retained = await hist.find({ doc_id }, { projection: { content: 0 } }).sort({ version: 1 }).toArray();
|
|
2540
2606
|
const rows = retained.map(r => ({ version: r.version, sha256: r.sha256 || null, size: r.size ?? null,
|
|
2541
2607
|
updated_at: r.updated_at || null, updated_by: r.updated_by || null, client_id: r.client_id || null, session_id: r.session_id || null, archived_at: r.archived_at || null,
|
|
2608
|
+
...(r.key_id ? { key_id: r.key_id } : {}),
|
|
2609
|
+
...(r.source_basis ? { source_basis: r.source_basis } : {}),
|
|
2542
2610
|
conformance: r.conformance ? r.conformance.verdict : null }));
|
|
2543
2611
|
return { doc_id, current_version: current ? current.version : null, retained_count: rows.length, retained: rows,
|
|
2544
2612
|
note: current ? null : 'No current document by this id; only retained revisions, if any.' };
|
|
@@ -2547,16 +2615,20 @@ export async function readDocHistory(doc_id, version = null, logger = null) {
|
|
|
2547
2615
|
return { doc_id, version, is_current: true, content: current.content, sha256: current.sha256, size: current.content.length,
|
|
2548
2616
|
updated_at: current.updated_at, updated_by: current.updated_by || null,
|
|
2549
2617
|
client_id: current.client_id || null, session_id: current.session_id || null,
|
|
2618
|
+
...(current.key_id ? { key_id: current.key_id } : {}),
|
|
2619
|
+
...(current.source_basis ? { source_basis: current.source_basis } : {}),
|
|
2550
2620
|
conformance: current.conformance || null };
|
|
2551
2621
|
}
|
|
2552
2622
|
// More than one archived row can carry a version when a write was retried;
|
|
2553
2623
|
// the most recently archived is the one the store last held at that number.
|
|
2554
2624
|
const row = await hist.find({ doc_id, version }).sort({ archived_at: -1 }).limit(1).next();
|
|
2555
|
-
if (!row) throw new ValidationError(`No retained revision ${version} of ${doc_id}
|
|
2625
|
+
if (!row) throw new ValidationError(`No retained revision ${version} of ${doc_id}`, { code: 'EMET-DOC-003' });
|
|
2556
2626
|
const integrity = row.sha256 ? (digest(row.content) === row.sha256) : 'unattested';
|
|
2557
2627
|
return { doc_id, version, is_current: false, content: row.content, sha256: row.sha256 || null, size: row.content.length,
|
|
2558
2628
|
updated_at: row.updated_at || null, updated_by: row.updated_by || null, archived_at: row.archived_at || null,
|
|
2559
2629
|
client_id: row.client_id || null, session_id: row.session_id || null,
|
|
2630
|
+
...(row.key_id ? { key_id: row.key_id } : {}),
|
|
2631
|
+
...(row.source_basis ? { source_basis: row.source_basis } : {}),
|
|
2560
2632
|
conformance: row.conformance || null,
|
|
2561
2633
|
// Re-hashed on read, as a layer row is: a retained revision that
|
|
2562
2634
|
// does not match its own digest is returned and flagged, never hidden.
|
|
@@ -2564,12 +2636,12 @@ export async function readDocHistory(doc_id, version = null, logger = null) {
|
|
|
2564
2636
|
} finally { await client.close(); }
|
|
2565
2637
|
} catch (error) {
|
|
2566
2638
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
2567
|
-
throw new DatabaseError(`Failed to read document history: ${error.message}`, 'read_doc_history');
|
|
2639
|
+
throw new DatabaseError(`Failed to read document history: ${error.message}`, 'read_doc_history', { code: 'EMET-DB-024' });
|
|
2568
2640
|
}
|
|
2569
2641
|
}
|
|
2570
2642
|
|
|
2571
2643
|
/**
|
|
2572
|
-
* Records are superseded, never amended (2026-09-26,
|
|
2644
|
+
* Records are superseded, never amended (2026-09-26, Alex: "enforce
|
|
2573
2645
|
* supersession ISO practices"). ISO 9001 7.5.3 / ISO 13485 4.2.5 separate
|
|
2574
2646
|
* DOCUMENTS, which are revised under control, from RECORDS, which are evidence
|
|
2575
2647
|
* of what happened and are not altered. The handoff is a record: it attests to
|
|
@@ -2601,22 +2673,23 @@ function _refuseRecordAmendment(doc_id, tool) {
|
|
|
2601
2673
|
`${tool}: ${doc_id} is a record. Records are superseded, not amended (ISO 9001 7.5.3 / 13485 4.2.5). ` +
|
|
2602
2674
|
`Issue a new revision with write_doc - the whole record, with \`supersedes\` set to the version now in force. ` +
|
|
2603
2675
|
`The prior revision is retained and marked obsolete. Nothing was changed.`
|
|
2604
|
-
);
|
|
2676
|
+
, { code: 'EMET-DOC-007' });
|
|
2605
2677
|
}
|
|
2606
2678
|
}
|
|
2607
2679
|
|
|
2608
2680
|
/**
|
|
2609
|
-
* The main records are the hub's (C1, 2026-10-01
|
|
2681
|
+
* The main records are the hub's (C1, 2026-10-01; review note section
|
|
2682
|
+
* 3.5). write_doc and patch_doc refuse the main HANDOFF.md or STATE.md when the
|
|
2610
2683
|
* write's source is a bot tag (bots/<tag>/HANDOFF.md listed in
|
|
2611
2684
|
* EMET_RECORD_DOCS), and nothing is written. So do the other doors that can
|
|
2612
|
-
* change a main record (the reviewer's F1
|
|
2685
|
+
* change a main record (the reviewer's F1 on PR 2): retire_doc, rename_doc (from
|
|
2613
2686
|
* or onto one) and accept_nonconformance - retire and rename set retired_by,
|
|
2614
2687
|
* not updated_by, so the close alone could not see them. The source is the one the door
|
|
2615
2688
|
* stamps as updated_by: the caller's, else EMET_SOURCE_TAG. A records rule like
|
|
2616
2689
|
* the record-amendment refusal above, so it applies in every graph mode.
|
|
2617
2690
|
*
|
|
2618
|
-
* Two further guards on the same doors (2026-10-01, the owner's approval to
|
|
2619
|
-
* make the bot tags fully functional; the reviewer's review of
|
|
2691
|
+
* Two further guards on the same doors (2026-10-01, the owner's 4:17 PM approval to
|
|
2692
|
+
* make the bot tags fully functional; the reviewer's review of PR 3):
|
|
2620
2693
|
* - REGISTERED HOSTS ONLY on the main records. With a source registry
|
|
2621
2694
|
* configured (EMET_SOURCE_TAGS, parsed as save_to_layer parses it), the
|
|
2622
2695
|
* main handoff and board take writes only from a registered tag. An
|
|
@@ -2630,7 +2703,21 @@ function _refuseRecordAmendment(doc_id, tool) {
|
|
|
2630
2703
|
* Hosts (the hub) keep writing anywhere under bots/.
|
|
2631
2704
|
*/
|
|
2632
2705
|
export function sourceRegistry() {
|
|
2633
|
-
|
|
2706
|
+
const env = String(setting('SOURCE_TAGS') ?? '').split(',').map((s) => s.trim()).filter((s) => s !== '');
|
|
2707
|
+
// Attribution v2: tags approved in emet/CLIENT_APPROVALS.md count as
|
|
2708
|
+
// registered once a registry exists (a fresh install with no registry stays open).
|
|
2709
|
+
return env.length ? [...new Set([...env, ...approvedTags()])] : env;
|
|
2710
|
+
}
|
|
2711
|
+
|
|
2712
|
+
/**
|
|
2713
|
+
* Attribution v2 (the second reader A3): a declared tag never gains rights beyond the login's
|
|
2714
|
+
* tag. A guard is run for every tag returned here and the write must pass all.
|
|
2715
|
+
*/
|
|
2716
|
+
export function rightsTags(tag) {
|
|
2717
|
+
const d = declaredAttribution();
|
|
2718
|
+
if (d && d.basis === 'subkey' && d.effective && tag === d.effective && d.login && d.login !== tag) return [tag, d.login];
|
|
2719
|
+
if (d && d.declared && tag === d.declared && d.login && d.login !== tag) return [tag, d.login];
|
|
2720
|
+
return [tag];
|
|
2634
2721
|
}
|
|
2635
2722
|
|
|
2636
2723
|
/**
|
|
@@ -2645,9 +2732,16 @@ export function sourceRegistry() {
|
|
|
2645
2732
|
export function resolvedSourceTag(caller) {
|
|
2646
2733
|
const bound = boundSourceTag();
|
|
2647
2734
|
const tag = typeof caller === 'string' ? caller.trim() : '';
|
|
2648
|
-
if (typeof bound === 'string' && bound) return { tag: bound, from: 'bound' };
|
|
2649
2735
|
if (bound === undefined) return { tag: tag || null, from: 'caller' };
|
|
2736
|
+
// Attribution v2: the per-request tag decided by attribution.preflight is the
|
|
2737
|
+
// stamp (declared, or generated for a login with none). Rights stay the
|
|
2738
|
+
// login's: see rightsTags().
|
|
2739
|
+
const d = declaredAttribution();
|
|
2740
|
+
if (d && d.basis === 'subkey' && d.effective) return { tag: d.effective, from: 'subkey', login: bound || null, key_id: d.keyId || null };
|
|
2741
|
+
if (d && d.declared && d.basis === 'declared' && tag === d.declared) return { tag, from: 'declared', login: bound || null };
|
|
2742
|
+
if (typeof bound === 'string' && bound) return { tag: bound, from: 'bound' };
|
|
2650
2743
|
if (tag && sourceRegistry().includes(tag)) return { tag, from: 'legacy' };
|
|
2744
|
+
if (d && d.basis === 'auto' && d.declared) return { tag: d.declared, from: 'auto' };
|
|
2651
2745
|
return { tag: null, from: 'legacy' };
|
|
2652
2746
|
}
|
|
2653
2747
|
|
|
@@ -2701,7 +2795,7 @@ export function refuseLookalikeDocId(doc_id, tool) {
|
|
|
2701
2795
|
throw new ValidationError(
|
|
2702
2796
|
`${tool}: doc_id ${JSON.stringify(doc_id)} ${why}. Doc ids are not paths and are not resolved; write the id ` +
|
|
2703
2797
|
`exactly as it is meant to be stored. Nothing was written.`
|
|
2704
|
-
);
|
|
2798
|
+
, { code: 'EMET-DOC-008' });
|
|
2705
2799
|
}
|
|
2706
2800
|
}
|
|
2707
2801
|
|
|
@@ -2715,7 +2809,27 @@ function mayCleanUpLookalike(tag) {
|
|
|
2715
2809
|
}
|
|
2716
2810
|
|
|
2717
2811
|
export function refuseBotMainRecord(doc_id, updated_by, tool, options = {}) {
|
|
2812
|
+
for (const t of rightsTags(updated_by)) refuseBotMainRecordOne(doc_id, t, tool, options);
|
|
2813
|
+
}
|
|
2814
|
+
function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
|
|
2718
2815
|
const tag = updated_by || setting('SOURCE_TAG') || null;
|
|
2816
|
+
// The client-approvals record is server-only (the second reader 4): no host writes,
|
|
2817
|
+
// patches, retires, renames, restores or accepts it.
|
|
2818
|
+
if (typeof doc_id === 'string' && FOLD(doc_id.normalize('NFKC')) === FOLD(APPROVALS_DOC) && !(options && options.approvalsRecord === true)) {
|
|
2819
|
+
throw new ValidationError(`${tool}: ${doc_id} is kept by the server (client approvals). Decide clients with emet_client_approve. Nothing was written.`, { code: 'EMET-DOC-009' });
|
|
2820
|
+
}
|
|
2821
|
+
// A3 without a registry (the second reader re-review): a declared or generated tag writes
|
|
2822
|
+
// under bots/ only inside bots/<its own tag>/ and only once approved.
|
|
2823
|
+
{
|
|
2824
|
+
const d = declaredAttribution();
|
|
2825
|
+
if (d && d.declared && tag === d.declared && (d.basis === 'declared' || d.basis === 'auto') &&
|
|
2826
|
+
typeof doc_id === 'string' && doc_id.startsWith('bots/')) {
|
|
2827
|
+
const approved = approvedTags().includes(tag) || sourceRegistry().includes(tag);
|
|
2828
|
+
if (!doc_id.startsWith(botRecordDir(tag)) || !approved) {
|
|
2829
|
+
throw new ValidationError(`${tool}: ${doc_id} is a bot record and "${tag}" is a ${approved ? 'declared tag outside its own folder' : 'declared tag not yet approved'} - a declared tag writes only bots/${tag}/ once approved. Nothing was written.`, { code: 'EMET-DOC-010' });
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
}
|
|
2719
2833
|
if (!(options.cleanup === true && mayCleanUpLookalike(tag))) refuseLookalikeDocId(doc_id, tool);
|
|
2720
2834
|
const bot = !!tag && isBotTag(tag);
|
|
2721
2835
|
if (bot && typeof doc_id === 'string' && doc_id.startsWith('bots/') && !doc_id.startsWith(botRecordDir(tag))) {
|
|
@@ -2723,9 +2837,9 @@ export function refuseBotMainRecord(doc_id, updated_by, tool, options = {}) {
|
|
|
2723
2837
|
`${tool}: ${doc_id} is outside ${botRecordDir(tag)} and ${tag} is a bot tag - a bot writes only its own ` +
|
|
2724
2838
|
`${botRecordDir(tag)} records; other bots' records and the roster are not its to change. ` +
|
|
2725
2839
|
`Hand it to the hub instead. Nothing was written.`
|
|
2726
|
-
);
|
|
2840
|
+
, { code: 'EMET-DOC-011' });
|
|
2727
2841
|
}
|
|
2728
|
-
// Registry guard on bots/ too (the reviewer's
|
|
2842
|
+
// Registry guard on bots/ too (the reviewer's PR 5 review; the second reader's fix (a), 2026-10-02): with EMET_SOURCE_TAGS
|
|
2729
2843
|
// set, a non-bot write under bots/ is refused unless its tag is registered; a missing source counts as
|
|
2730
2844
|
// unregistered. Without this, a misspelled or unregistered tag is not a bot tag, so the cross-bot guard
|
|
2731
2845
|
// above never fires and it can write any bot's records or the roster. A listed bot is already fenced to
|
|
@@ -2735,7 +2849,7 @@ export function refuseBotMainRecord(doc_id, updated_by, tool, options = {}) {
|
|
|
2735
2849
|
throw new ValidationError(
|
|
2736
2850
|
`${tool}: ${doc_id} is a bot record and ${tag ? `"${tag}" is not a registered source tag` : 'this write names no source tag'} - ` +
|
|
2737
2851
|
`only a registered host or the bot itself writes under bots/. Nothing was written.`
|
|
2738
|
-
);
|
|
2852
|
+
, { code: 'EMET-DOC-012' });
|
|
2739
2853
|
}
|
|
2740
2854
|
if (!mainRecordIds().includes(doc_id)) return;
|
|
2741
2855
|
if (bot) {
|
|
@@ -2743,7 +2857,7 @@ export function refuseBotMainRecord(doc_id, updated_by, tool, options = {}) {
|
|
|
2743
2857
|
`${tool}: ${doc_id} is a main record and ${tag} is a bot tag - a bot session closes against ` +
|
|
2744
2858
|
`${botRecordDir(tag)} records; the main handoff and board are the hub's. Write the bot's own ` +
|
|
2745
2859
|
`${botRecordDir(tag)}HANDOFF.md instead. Nothing was written.`
|
|
2746
|
-
);
|
|
2860
|
+
, { code: 'EMET-DOC-013' });
|
|
2747
2861
|
}
|
|
2748
2862
|
if (options && options.serverProvision === true) return;
|
|
2749
2863
|
if (registry.length && !(tag && registry.includes(tag))) {
|
|
@@ -2751,44 +2865,53 @@ export function refuseBotMainRecord(doc_id, updated_by, tool, options = {}) {
|
|
|
2751
2865
|
`${tool}: ${doc_id} is a main record and ` +
|
|
2752
2866
|
`${tag ? `"${tag}" is not a registered source tag` : 'this write names no source tag'} - only a registered ` +
|
|
2753
2867
|
`host writes the main handoff and board. Pass the host's registered \`source\` (EMET_SOURCE_TAGS). Nothing was written.`
|
|
2754
|
-
);
|
|
2868
|
+
, { code: 'EMET-DOC-014' });
|
|
2755
2869
|
}
|
|
2756
2870
|
}
|
|
2757
2871
|
|
|
2758
2872
|
/**
|
|
2759
|
-
* retire_doc and rename_doc are not bot tools at all (
|
|
2760
|
-
* decision 1, as relayed: "retire_doc isn't needed for bots: keep it
|
|
2761
|
-
*
|
|
2762
|
-
*
|
|
2873
|
+
* retire_doc and rename_doc are not bot tools at all (Alex, 2026-10-01 4:27 PM
|
|
2874
|
+
* ET, decision 1, as relayed: "retire_doc isn't needed for bots: keep it
|
|
2875
|
+
* Alex/hub only and out of every bot profile"; procedural ref 407; stage 1 of the
|
|
2876
|
+
* ref 358 startup amendment, admitted by the reviewer 2026-10-02). A profile is not a
|
|
2763
2877
|
* security boundary, so the door refuses them under ANY bot tag, for every
|
|
2764
|
-
* doc_id - not only the main records refuseBotMainRecord covers.
|
|
2765
|
-
* covers retire_doc only; rename_doc stays owner-only under
|
|
2766
|
-
* (owner-confirmed 2026-10-02: every other owner-only tool is
|
|
2878
|
+
* doc_id - not only the main records refuseBotMainRecord covers. ref 407(1)
|
|
2879
|
+
* covers retire_doc only; rename_doc stays owner-only under procedural ref 409
|
|
2880
|
+
* (owner-confirmed 2026-10-02 the recorded time: every other owner-only tool is
|
|
2767
2881
|
* unchanged), and it retires its old id internally, so it is refused too. The tag is the
|
|
2768
2882
|
* one the door would stamp: the caller's, else EMET_SOURCE_TAG. Hosts and the
|
|
2769
2883
|
* hub have no bots/<tag>/HANDOFF.md record and are unaffected. Nothing is
|
|
2770
2884
|
* written when refused.
|
|
2771
2885
|
*/
|
|
2772
2886
|
export function refuseBotRetireRename(tag, tool) {
|
|
2887
|
+
for (const t of rightsTags(tag)) refuseBotRetireRenameOne(t, tool);
|
|
2888
|
+
}
|
|
2889
|
+
function refuseBotRetireRenameOne(tag, tool) {
|
|
2773
2890
|
const t = tag || setting('SOURCE_TAG') || null;
|
|
2774
2891
|
if (!t || !isBotTag(t)) return;
|
|
2892
|
+
if (tool === 'retire_doc') {
|
|
2893
|
+
throw new ValidationError(
|
|
2894
|
+
'source',
|
|
2895
|
+
`${tool} is not a bot tool: ${t} is a bot tag, and ` +
|
|
2896
|
+
`retiring documents is the owner's and the hub's (decision 1, procedural ref 407 item 1)` +
|
|
2897
|
+
`. Ask the hub. Nothing was changed.`
|
|
2898
|
+
, { code: 'EMET-MEM-019' });
|
|
2899
|
+
}
|
|
2775
2900
|
throw new ValidationError(
|
|
2776
2901
|
'source',
|
|
2777
2902
|
`${tool} is not a bot tool: ${t} is a bot tag, and ` +
|
|
2778
|
-
(
|
|
2779
|
-
? `retiring documents is the owner's and the hub's (decision 1, the owner's decision record item 1)`
|
|
2780
|
-
: `renaming documents stays owner-only (the owner's decision record)`) +
|
|
2903
|
+
`renaming documents stays owner-only (procedural ref 409)` +
|
|
2781
2904
|
`. Ask the hub. Nothing was changed.`
|
|
2782
|
-
);
|
|
2905
|
+
, { code: 'EMET-MEM-020' });
|
|
2783
2906
|
}
|
|
2784
2907
|
|
|
2785
2908
|
export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint = null, logger = null, options = {}) {
|
|
2786
2909
|
try {
|
|
2787
|
-
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
|
|
2910
|
+
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
|
|
2788
2911
|
// write_doc, patch_doc (which lands here) and rename_doc's copy (reissued_from).
|
|
2789
|
-
refuseBotMainRecord(doc_id, updated_by, options && options.reissued_from ? 'rename_doc' : 'write_doc', options && options.serverProvision === true ? { serverProvision: true } : {});
|
|
2790
|
-
if (typeof rawContent !== 'string' || rawContent.length === 0) throw new ValidationError('content must be a non-empty string');
|
|
2791
|
-
if (rawContent.length > 2000000) throw new ValidationError('content exceeds 2MB limit');
|
|
2912
|
+
refuseBotMainRecord(doc_id, updated_by, options && options.reissued_from ? 'rename_doc' : 'write_doc', options && options.serverProvision === true ? { serverProvision: true, ...(options.approvalsRecord === true ? { approvalsRecord: true } : {}) } : {});
|
|
2913
|
+
if (typeof rawContent !== 'string' || rawContent.length === 0) throw new ValidationError('content must be a non-empty string', { code: 'EMET-DOC-015' });
|
|
2914
|
+
if (rawContent.length > 2000000) throw new ValidationError('content exceeds 2MB limit', { code: 'EMET-DOC-016' });
|
|
2792
2915
|
// patch_doc lands here too, so one
|
|
2793
2916
|
// scrub covers every document write. The digest is of the stored text.
|
|
2794
2917
|
const redaction = redactWithReport(rawContent);
|
|
@@ -2798,8 +2921,17 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
|
|
|
2798
2921
|
const signature = signDigests(sha256, '', signingKey);
|
|
2799
2922
|
const { client, col, hist } = await _docsClient();
|
|
2800
2923
|
try {
|
|
2924
|
+
if (typeof doc_id === 'string' && doc_id.startsWith('areas/')) {
|
|
2925
|
+
const { assertAreaOwner } = await import('./pages.js');
|
|
2926
|
+
await assertAreaOwner(client.db(MONGODB_DB), 'write_doc');
|
|
2927
|
+
}
|
|
2801
2928
|
const prev = await col.findOne({ doc_id });
|
|
2802
2929
|
const version = (prev && prev.version ? prev.version : 0) + 1;
|
|
2930
|
+
// Compare-and-set for the client-approvals record (the second reader round 3): checked
|
|
2931
|
+
// here before anything is archived, and again atomically in the update filter.
|
|
2932
|
+
const casOn = options && options.approvalsRecord === true && Object.prototype.hasOwnProperty.call(options, 'expectedVersion');
|
|
2933
|
+
const casConflict = () => { const e = new ValidationError(`${doc_id} changed under this write (compare-and-set). Nothing was written.`); e.versionConflict = true; return e; };
|
|
2934
|
+
if (casOn && ((prev ? prev.version : null) ?? null) !== (options.expectedVersion ?? null)) throw casConflict();
|
|
2803
2935
|
// A record in force is superseded only by a revision that names it.
|
|
2804
2936
|
// Checked before anything is archived, so a refused write leaves no trace.
|
|
2805
2937
|
if (prev && isRecordDoc(doc_id) && options && options.restore_of && (options.supersedes === undefined || options.supersedes === null)) {
|
|
@@ -2811,56 +2943,56 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
|
|
|
2811
2943
|
throw new ValidationError(
|
|
2812
2944
|
`write_doc: ${doc_id} is a record and v${prev.version} is in force. A new revision must name what it ` +
|
|
2813
2945
|
`supersedes - pass supersedes: ${prev.version}. Nothing was changed.`
|
|
2814
|
-
);
|
|
2946
|
+
, { code: 'EMET-DOC-017' });
|
|
2815
2947
|
}
|
|
2816
2948
|
if (Number(named) !== prev.version) {
|
|
2817
2949
|
throw new ValidationError(
|
|
2818
2950
|
`write_doc: ${doc_id} - supersedes names v${named}, but v${prev.version} is in force. Re-read the record ` +
|
|
2819
2951
|
`and supersede the current revision. Nothing was changed.`
|
|
2820
|
-
);
|
|
2952
|
+
, { code: 'EMET-DOC-018' });
|
|
2821
2953
|
}
|
|
2822
2954
|
const reason = options && options.reason;
|
|
2823
2955
|
if (typeof reason !== 'string' || reason.trim().length < 10) {
|
|
2824
2956
|
throw new ValidationError(
|
|
2825
2957
|
`write_doc: ${doc_id} is a record. A new revision needs reason (at least 10 characters) as well as supersedes. Nothing was changed.`
|
|
2826
|
-
);
|
|
2958
|
+
, { code: 'EMET-DOC-019' });
|
|
2827
2959
|
}
|
|
2828
2960
|
}
|
|
2829
2961
|
const registry = sourceRegistry();
|
|
2830
|
-
const tag = updated_by || '';
|
|
2831
|
-
const registered = registry.length === 0 || registry.includes(tag);
|
|
2832
|
-
const ownBotFolder = isBotTag(updated_by) && doc_id.startsWith(`bots/${updated_by}/`);
|
|
2833
2962
|
const serverProvision = options && options.serverProvision === true;
|
|
2834
|
-
|
|
2835
|
-
|
|
2963
|
+
// Attribution v2 (A3): the declared tag and the login's tag must both pass.
|
|
2964
|
+
const passes = (t) => registry.length === 0 || registry.includes(t || '') || (isBotTag(t) && doc_id.startsWith(`bots/${t}/`));
|
|
2965
|
+
if (!rightsTags(updated_by).every(passes) && !serverProvision && !(isDropDoc(doc_id) && !prev)) {
|
|
2966
|
+
throw new ValidationError(`write_doc: ${updated_by || 'no source'} is not a registered source. This session may read, and may write a new drop only. Nothing was written.`, { code: 'EMET-DOC-020' });
|
|
2836
2967
|
}
|
|
2837
2968
|
if (isDropDoc(doc_id) && !prev) {
|
|
2838
2969
|
const { writerStamp } = await import('./persons.js');
|
|
2839
2970
|
const bucket = dropBucket(writerStamp().client_id, updated_by);
|
|
2840
2971
|
const day = nyDay(new Date());
|
|
2841
2972
|
const same = (await col.find({ doc_id: { $regex: '^drops/' } }).toArray()).filter((d) => (d.drop_bucket || dropBucket(d.client_id, d.updated_by)) === bucket && nyDay(d.updated_at instanceof Date ? d.updated_at : new Date(d.updated_at || 0)) === day);
|
|
2842
|
-
if (same.length >= 20) throw new ValidationError(`write_doc: this connected app already wrote 20 drops today. Nothing was written
|
|
2973
|
+
if (same.length >= 20) throw new ValidationError(`write_doc: this connected app already wrote 20 drops today. Nothing was written.`, { code: 'EMET-DOC-021' });
|
|
2843
2974
|
options = { ...options, drop_bucket: bucket };
|
|
2844
2975
|
}
|
|
2845
2976
|
const floorExempt = options && options.provision;
|
|
2846
|
-
const internal = options && (options.provision || options.edited || options.setupReissue || options.restore_of);
|
|
2977
|
+
const internal = options && (options.provision || options.edited || options.setupReissue || options.restore_of || (options.approvalsRecord === true && options.serverProvision === true && doc_id === APPROVALS_DOC));
|
|
2847
2978
|
if (options && options.provision && prev && doc_id === stateDoc()) {
|
|
2848
|
-
throw new ValidationError('The board already exists. Provision does not replace it. Nothing was written.');
|
|
2979
|
+
throw new ValidationError('The board already exists. Provision does not replace it. Nothing was written.', { code: 'EMET-MEM-021' });
|
|
2849
2980
|
}
|
|
2850
2981
|
if (doc_id === stateDoc() && !(options && (options.provision || options.edited || options.restore_of))) {
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2982
|
+
if (prev) {
|
|
2983
|
+
throw new ValidationError('The board is never written. Edit it with patch_doc, with `reason` (and `origin` for an added row). Nothing was written.', { code: 'EMET-MEM-022' });
|
|
2984
|
+
}
|
|
2985
|
+
throw new ValidationError('The board is provisioned by the server at setup (emet_setup_complete). Nothing was written.', { code: 'EMET-MEM-023' });
|
|
2854
2986
|
}
|
|
2855
2987
|
if (prev && isWorkingDoc(doc_id) && !internal) {
|
|
2856
2988
|
throw new ValidationError(
|
|
2857
2989
|
`write_doc: ${doc_id} exists, so it is edited, not rewritten. Use patch_doc with \`reason\`. Nothing was written.`
|
|
2858
|
-
);
|
|
2990
|
+
, { code: 'EMET-DOC-022' });
|
|
2859
2991
|
}
|
|
2860
2992
|
if (isDropDoc(doc_id) && (prev || (options && options.restore_of))) {
|
|
2861
2993
|
throw new ValidationError(
|
|
2862
2994
|
`write_doc: ${doc_id} is a drop and already exists, retired drops included. A drop is never patched or restored. Use a new id. Nothing was written.`
|
|
2863
|
-
);
|
|
2995
|
+
, { code: 'EMET-DOC-023' });
|
|
2864
2996
|
}
|
|
2865
2997
|
if (isGovernedByShippedCopy(doc_id) && !(options && options.provision)) {
|
|
2866
2998
|
const { readFileSync } = await import('node:fs');
|
|
@@ -2868,7 +3000,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
|
|
|
2868
3000
|
let shipped = '';
|
|
2869
3001
|
try { shipped = readFileSync(shippedPath, 'utf8'); } catch { shipped = ''; }
|
|
2870
3002
|
if (content !== shipped) {
|
|
2871
|
-
throw new ValidationError(`write_doc: ${doc_id} is governed by the copy shipped with this release. Only that text may be stored. Nothing was written
|
|
3003
|
+
throw new ValidationError(`write_doc: ${doc_id} is governed by the copy shipped with this release. Only that text may be stored. Nothing was written.`, { code: 'EMET-DOC-024' });
|
|
2872
3004
|
}
|
|
2873
3005
|
}
|
|
2874
3006
|
const sid = (options && options.session_id) || null;
|
|
@@ -2884,7 +3016,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
|
|
|
2884
3016
|
const pct = Math.floor((content.length / baseline) * 100);
|
|
2885
3017
|
throw new ValidationError(
|
|
2886
3018
|
`This change would leave ${doc_id} at ${pct}% of its size when this session first touched it. Condensing below half is not done on the EMET server. Nothing was written.`
|
|
2887
|
-
);
|
|
3019
|
+
, { code: 'EMET-DOC-025' });
|
|
2888
3020
|
}
|
|
2889
3021
|
// Cross-session floor. The per-session floor is measured from this
|
|
2890
3022
|
// session's first touch, so a new session can shrink a document once.
|
|
@@ -2903,7 +3035,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
|
|
|
2903
3035
|
const pct = Math.floor((content.length / peak) * 100);
|
|
2904
3036
|
throw new ValidationError(
|
|
2905
3037
|
`This change would leave ${doc_id} at ${pct}% of its largest size in the last 24 hours. A write may not fall below half of that peak. Nothing was written.`
|
|
2906
|
-
);
|
|
3038
|
+
, { code: 'EMET-DOC-026' });
|
|
2907
3039
|
}
|
|
2908
3040
|
const sizeSamples = recentSamples.slice();
|
|
2909
3041
|
if (prev) sizeSamples.push({ size: String(prev.content || '').length, at: prev.updated_at || new Date() });
|
|
@@ -2916,7 +3048,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
|
|
|
2916
3048
|
const now = new Date();
|
|
2917
3049
|
// Validation runs HERE: after redaction, on the exact text that will be
|
|
2918
3050
|
// stored, with the previous revision already in hand for the
|
|
2919
|
-
// carry-forward comparison. It marks and never rejects, so its
|
|
3051
|
+
// carry-forward comparison. It marks and never rejects (ref 304), so its
|
|
2920
3052
|
// result is a field on the row rather than a branch in this function.
|
|
2921
3053
|
// Writing the field whole also enforces L6 - the fresh object carries no
|
|
2922
3054
|
// acceptance, so an acceptance covers the one revision it was given to.
|
|
@@ -2957,11 +3089,31 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
|
|
|
2957
3089
|
retired: false,
|
|
2958
3090
|
size_note: 'baseline is the size when this session first touched the document'
|
|
2959
3091
|
};
|
|
3092
|
+
const attr = declaredAttribution();
|
|
3093
|
+
if (attr && attr.basis === 'subkey' && attr.keyId) {
|
|
3094
|
+
writtenRow.key_id = attr.keyId;
|
|
3095
|
+
writtenRow.source_basis = 'subkey';
|
|
3096
|
+
}
|
|
2960
3097
|
if (options && options.provision && doc_id === stateDoc()) {
|
|
2961
3098
|
const ins = await col.updateOne({ doc_id }, { $setOnInsert: writtenRow }, { upsert: true });
|
|
2962
3099
|
if (ins && ins.upsertedCount === 0) {
|
|
2963
|
-
throw new ValidationError('The board already exists. Provision does not replace it. Nothing was written.');
|
|
3100
|
+
throw new ValidationError('The board already exists. Provision does not replace it. Nothing was written.', { code: 'EMET-MEM-021' });
|
|
3101
|
+
}
|
|
3102
|
+
} else if (casOn) {
|
|
3103
|
+
let res;
|
|
3104
|
+
try {
|
|
3105
|
+
res = options.expectedVersion == null
|
|
3106
|
+
// the second reader delta M1: documents.doc_id has no unique index, so the first
|
|
3107
|
+
// create keys on a deterministic _id; _id is always unique, so a
|
|
3108
|
+
// second racing insert matches it (or hits a duplicate key) and loses.
|
|
3109
|
+
? await col.updateOne({ _id: `${APPROVALS_DOC}#current` }, { $setOnInsert: writtenRow }, { upsert: true })
|
|
3110
|
+
: await col.updateOne({ doc_id, version: options.expectedVersion }, { $set: writtenRow }, { upsert: false });
|
|
3111
|
+
} catch (e) {
|
|
3112
|
+
if (e && (e.code === 11000 || /duplicate key/i.test(String(e.message)))) throw casConflict();
|
|
3113
|
+
throw e;
|
|
2964
3114
|
}
|
|
3115
|
+
const won = options.expectedVersion == null ? (res && res.upsertedCount === 1) : (res && res.matchedCount === 1);
|
|
3116
|
+
if (!won) throw casConflict();
|
|
2965
3117
|
} else {
|
|
2966
3118
|
await col.updateOne({ doc_id }, { $set: writtenRow }, { upsert: true });
|
|
2967
3119
|
}
|
|
@@ -2974,8 +3126,9 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
|
|
|
2974
3126
|
redacted: redaction.hits, conformance };
|
|
2975
3127
|
} finally { await client.close(); }
|
|
2976
3128
|
} catch (error) {
|
|
3129
|
+
if (error && error.versionConflict) throw error;
|
|
2977
3130
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
2978
|
-
throw new DatabaseError(`Failed to write document: ${error.message}`, 'write_doc');
|
|
3131
|
+
throw new DatabaseError(`Failed to write document: ${error.message}`, 'write_doc', { code: 'EMET-DB-025' });
|
|
2979
3132
|
}
|
|
2980
3133
|
}
|
|
2981
3134
|
|
|
@@ -3009,7 +3162,7 @@ export async function listDocs(prefix = null, logger = null, include_retired = f
|
|
|
3009
3162
|
} finally { await client.close(); }
|
|
3010
3163
|
} catch (error) {
|
|
3011
3164
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
3012
|
-
throw new DatabaseError(`Failed to list documents: ${error.message}`, 'list_docs');
|
|
3165
|
+
throw new DatabaseError(`Failed to list documents: ${error.message}`, 'list_docs', { code: 'EMET-DB-026' });
|
|
3013
3166
|
}
|
|
3014
3167
|
}
|
|
3015
3168
|
|
|
@@ -3052,17 +3205,23 @@ export async function listDocs(prefix = null, logger = null, include_retired = f
|
|
|
3052
3205
|
*/
|
|
3053
3206
|
export async function retireDoc(doc_id, reason = null, retired_by = null, logger = null, options = {}) {
|
|
3054
3207
|
try {
|
|
3055
|
-
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
|
|
3208
|
+
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
|
|
3209
|
+
if (doc_id.startsWith('areas/')) {
|
|
3210
|
+
const { assertAreaOwner } = await import('./pages.js');
|
|
3211
|
+
const opened = await _docsClient();
|
|
3212
|
+
try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'retire_doc'); }
|
|
3213
|
+
finally { await opened.client.close(); }
|
|
3214
|
+
}
|
|
3056
3215
|
refuseBotMainRecord(doc_id, retired_by, 'retire_doc', { cleanup: true });
|
|
3057
3216
|
refuseBotRetireRename(retired_by, 'retire_doc');
|
|
3058
|
-
if (doc_id === stateDoc()) throw new ValidationError('retire_doc: the board is never retired. Edit it with patch_doc and a reason. Nothing was changed.');
|
|
3059
|
-
if (!isDropDoc(doc_id) && !(options && options.fromRename)) throw new ValidationError(`retire_doc: ${doc_id} is not a drop. Working documents are edited, not retired. Nothing was changed
|
|
3060
|
-
if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('retire_doc needs reason (at least 10 characters), naming where the drop went. Nothing was changed.');
|
|
3217
|
+
if (doc_id === stateDoc()) throw new ValidationError('retire_doc: the board is never retired. Edit it with patch_doc and a reason. Nothing was changed.', { code: 'EMET-DOC-027' });
|
|
3218
|
+
if (!isDropDoc(doc_id) && !(options && options.fromRename)) throw new ValidationError(`retire_doc: ${doc_id} is not a drop. Working documents are edited, not retired. Nothing was changed.`, { code: 'EMET-DOC-028' });
|
|
3219
|
+
if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('retire_doc needs reason (at least 10 characters), naming where the drop went. Nothing was changed.', { code: 'EMET-DOC-029' });
|
|
3061
3220
|
|
|
3062
3221
|
const { client, col } = await _docsClient();
|
|
3063
3222
|
try {
|
|
3064
3223
|
const doc = await col.findOne({ doc_id });
|
|
3065
|
-
if (!doc) throw new ValidationError(`Document not found: ${doc_id}
|
|
3224
|
+
if (!doc) throw new ValidationError(`Document not found: ${doc_id}`, { code: 'EMET-DOC-002' });
|
|
3066
3225
|
if (doc.retired) {
|
|
3067
3226
|
return { doc_id, retired: true, already_retired: true, verified: true,
|
|
3068
3227
|
retired_at: doc.retired_at, retired_reason: doc.retired_reason || null,
|
|
@@ -3084,10 +3243,10 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
|
|
|
3084
3243
|
// digest are re-checked too - retiring must not touch either.
|
|
3085
3244
|
const check = await col.findOne({ doc_id });
|
|
3086
3245
|
if (!check || check.retired !== true) {
|
|
3087
|
-
throw new DatabaseError(`Retirement mark did not persist: ${doc_id}`, 'retire_doc');
|
|
3246
|
+
throw new DatabaseError(`Retirement mark did not persist: ${doc_id}`, 'retire_doc', { code: 'EMET-DB-027' });
|
|
3088
3247
|
}
|
|
3089
3248
|
if (check.sha256 !== doc.sha256 || check.version !== doc.version) {
|
|
3090
|
-
throw new DatabaseError(`Retiring altered the document: ${doc_id}`, 'retire_doc');
|
|
3249
|
+
throw new DatabaseError(`Retiring altered the document: ${doc_id}`, 'retire_doc', { code: 'EMET-DB-028' });
|
|
3091
3250
|
}
|
|
3092
3251
|
|
|
3093
3252
|
// L5 - retirement is not an escape hatch. retireDoc is the one document
|
|
@@ -3114,32 +3273,38 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
|
|
|
3114
3273
|
} finally { await client.close(); }
|
|
3115
3274
|
} catch (error) {
|
|
3116
3275
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
3117
|
-
throw new DatabaseError(`Failed to retire document: ${error.message}`, 'retire_doc');
|
|
3276
|
+
throw new DatabaseError(`Failed to retire document: ${error.message}`, 'retire_doc', { code: 'EMET-DB-029' });
|
|
3118
3277
|
}
|
|
3119
3278
|
}
|
|
3120
3279
|
|
|
3121
3280
|
export async function renameDoc(old_id, new_id, updated_by = null, logger = null, reason = null, options = {}) {
|
|
3122
3281
|
try {
|
|
3123
|
-
if (!old_id || typeof old_id !== 'string') throw new ValidationError('old_id must be a non-empty string');
|
|
3124
|
-
if (!new_id || typeof new_id !== 'string') throw new ValidationError('new_id must be a non-empty string');
|
|
3125
|
-
if (old_id === new_id) throw new ValidationError('old_id and new_id name the same document');
|
|
3282
|
+
if (!old_id || typeof old_id !== 'string') throw new ValidationError('old_id must be a non-empty string', { code: 'EMET-DOC-030' });
|
|
3283
|
+
if (!new_id || typeof new_id !== 'string') throw new ValidationError('new_id must be a non-empty string', { code: 'EMET-DOC-031' });
|
|
3284
|
+
if (old_id === new_id) throw new ValidationError('old_id and new_id name the same document', { code: 'EMET-DOC-032' });
|
|
3285
|
+
if ((typeof old_id === 'string' && old_id.startsWith('areas/')) || (typeof new_id === 'string' && new_id.startsWith('areas/'))) {
|
|
3286
|
+
const { assertAreaOwner } = await import('./pages.js');
|
|
3287
|
+
const opened = await _docsClient();
|
|
3288
|
+
try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'rename_doc'); }
|
|
3289
|
+
finally { await opened.client.close(); }
|
|
3290
|
+
}
|
|
3126
3291
|
refuseBotMainRecord(old_id, updated_by, 'rename_doc', { cleanup: true });
|
|
3127
3292
|
refuseBotMainRecord(new_id, updated_by, 'rename_doc');
|
|
3128
3293
|
refuseBotRetireRename(updated_by, 'rename_doc');
|
|
3129
|
-
if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('rename_doc needs reason (at least 10 characters). Nothing was changed.');
|
|
3130
|
-
if (old_id === stateDoc() || new_id === stateDoc()) throw new ValidationError('rename_doc: the board is never renamed. Nothing was changed.');
|
|
3131
|
-
if (isDropDoc(old_id) || isDropDoc(new_id)) throw new ValidationError('rename_doc: a drop is write-once. Use a new id. Nothing was changed.');
|
|
3294
|
+
if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('rename_doc needs reason (at least 10 characters). Nothing was changed.', { code: 'EMET-DOC-033' });
|
|
3295
|
+
if (old_id === stateDoc() || new_id === stateDoc()) throw new ValidationError('rename_doc: the board is never renamed. Nothing was changed.', { code: 'EMET-DOC-034' });
|
|
3296
|
+
if (isDropDoc(old_id) || isDropDoc(new_id)) throw new ValidationError('rename_doc: a drop is write-once. Use a new id. Nothing was changed.', { code: 'EMET-DOC-035' });
|
|
3132
3297
|
|
|
3133
3298
|
let content, path_hint;
|
|
3134
3299
|
const { client, col } = await _docsClient();
|
|
3135
3300
|
try {
|
|
3136
3301
|
const source = await col.findOne({ doc_id: old_id });
|
|
3137
|
-
if (!source) throw new ValidationError(`Document not found: ${old_id}
|
|
3302
|
+
if (!source) throw new ValidationError(`Document not found: ${old_id}`, { code: 'EMET-DOC-002' });
|
|
3138
3303
|
// Never clobber. A rename onto an occupied id is a MERGE decision, and a
|
|
3139
3304
|
// merge is not something to guess at on the caller's behalf.
|
|
3140
3305
|
const occupied = await col.findOne({ doc_id: new_id });
|
|
3141
3306
|
if (occupied) {
|
|
3142
|
-
throw new ValidationError(`Destination already exists: ${new_id} (version ${occupied.version}). Rename refused; nothing was changed
|
|
3307
|
+
throw new ValidationError(`Destination already exists: ${new_id} (version ${occupied.version}). Rename refused; nothing was changed.`, { code: 'EMET-DOC-036' });
|
|
3143
3308
|
}
|
|
3144
3309
|
content = source.content;
|
|
3145
3310
|
path_hint = source.path_hint || null;
|
|
@@ -3169,17 +3334,17 @@ export async function renameDoc(old_id, new_id, updated_by = null, logger = null
|
|
|
3169
3334
|
};
|
|
3170
3335
|
} catch (error) {
|
|
3171
3336
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
3172
|
-
throw new DatabaseError(`Failed to rename document: ${error.message}`, 'rename_doc');
|
|
3337
|
+
throw new DatabaseError(`Failed to rename document: ${error.message}`, 'rename_doc', { code: 'EMET-DB-030' });
|
|
3173
3338
|
}
|
|
3174
3339
|
}
|
|
3175
3340
|
|
|
3176
3341
|
async function unretiredBootDrops(session_id) {
|
|
3177
3342
|
if (!session_id || typeof session_id !== 'string' || !String(session_id).trim()) {
|
|
3178
|
-
throw new ValidationError('a board edit or restore needs session_id from emet_session_open, with a verified drop list. Nothing was written.');
|
|
3343
|
+
throw new ValidationError('a board edit or restore needs session_id from emet_session_open, with a verified drop list. Nothing was written.', { code: 'EMET-MEM-024' });
|
|
3179
3344
|
}
|
|
3180
3345
|
const base = String(session_id).replace(/_verbatim_part\d+$/, '').trim();
|
|
3181
3346
|
if (!base) {
|
|
3182
|
-
throw new ValidationError('a board edit or restore needs session_id from emet_session_open, with a verified drop list. Nothing was written.');
|
|
3347
|
+
throw new ValidationError('a board edit or restore needs session_id from emet_session_open, with a verified drop list. Nothing was written.', { code: 'EMET-MEM-024' });
|
|
3183
3348
|
}
|
|
3184
3349
|
const { COLLECTION_PREFIX } = await import('./database.js');
|
|
3185
3350
|
const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: dropListTimeoutMs(), maxPoolSize: 10 });
|
|
@@ -3187,7 +3352,7 @@ async function unretiredBootDrops(session_id) {
|
|
|
3187
3352
|
const db = client.db(MONGODB_DB);
|
|
3188
3353
|
const row = await db.collection(`${COLLECTION_PREFIX}sessions`).findOne({ _id: base });
|
|
3189
3354
|
if (!row || row.drops_unverified === true || !Array.isArray(row.drops_seen)) {
|
|
3190
|
-
throw new ValidationError('unhandled drops could not be loaded at this session boot, so the board cannot be edited or restored until the list is known. Nothing was written.');
|
|
3355
|
+
throw new ValidationError('unhandled drops could not be loaded at this session boot, so the board cannot be edited or restored until the list is known. Nothing was written.', { code: 'EMET-MEM-025' });
|
|
3191
3356
|
}
|
|
3192
3357
|
const listed = row.drops_seen;
|
|
3193
3358
|
if (!listed.length) return [];
|
|
@@ -3199,28 +3364,28 @@ async function unretiredBootDrops(session_id) {
|
|
|
3199
3364
|
export async function restoreDoc(doc_id, version, updated_by = null, logger = null, reason = null, options = {}) {
|
|
3200
3365
|
refuseBotMainRecord(doc_id, updated_by, 'restore_doc');
|
|
3201
3366
|
refuseBotRetireRename(updated_by, 'restore_doc');
|
|
3202
|
-
if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('restore_doc needs reason (at least 10 characters). Nothing was written.');
|
|
3203
|
-
if (!updated_by) throw new ValidationError('restore_doc needs a source. Nothing was written.');
|
|
3204
|
-
if (isDropDoc(doc_id)) throw new ValidationError('restore_doc: a drop is never restored. Nothing was written.');
|
|
3205
|
-
if (isRecordDoc(doc_id)) throw new ValidationError('restore_doc: a record is not restored. Records are superseded via revise_memory, not restored. Nothing was written.');
|
|
3206
|
-
if (isGovernedByShippedCopy(doc_id)) throw new ValidationError('restore_doc: a shipped copy is not restored. Nothing was written.');
|
|
3367
|
+
if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('restore_doc needs reason (at least 10 characters). Nothing was written.', { code: 'EMET-DOC-037' });
|
|
3368
|
+
if (!updated_by) throw new ValidationError('restore_doc needs a source. Nothing was written.', { code: 'EMET-DOC-038' });
|
|
3369
|
+
if (isDropDoc(doc_id)) throw new ValidationError('restore_doc: a drop is never restored. Nothing was written.', { code: 'EMET-DOC-039' });
|
|
3370
|
+
if (isRecordDoc(doc_id)) throw new ValidationError('restore_doc: a record is not restored. Records are superseded via revise_memory, not restored. Nothing was written.', { code: 'EMET-DOC-040' });
|
|
3371
|
+
if (isGovernedByShippedCopy(doc_id)) throw new ValidationError('restore_doc: a shipped copy is not restored. Nothing was written.', { code: 'EMET-DOC-041' });
|
|
3207
3372
|
const allowed = (setting('RESTORE_TAGS') || setting('SOURCE_TAG') || '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
3208
|
-
if (!allowed.includes(updated_by)) throw new ValidationError(`restore_doc: ${updated_by} is not in EMET_RESTORE_TAGS. Nothing was written
|
|
3373
|
+
if (!allowed.includes(updated_by)) throw new ValidationError(`restore_doc: ${updated_by} is not in EMET_RESTORE_TAGS. Nothing was written.`, { code: 'EMET-DOC-042' });
|
|
3209
3374
|
const prior = await readDocHistory(doc_id, version, logger);
|
|
3210
|
-
if (!prior || typeof prior.content !== 'string') throw new ValidationError(`No retained revision ${version} of ${doc_id}
|
|
3211
|
-
if (prior.integrity !== true) throw new ValidationError(`restore_doc: retained revision ${version} of ${doc_id} does not match its digest. Nothing was written
|
|
3375
|
+
if (!prior || typeof prior.content !== 'string') throw new ValidationError(`No retained revision ${version} of ${doc_id}`, { code: 'EMET-DOC-003' });
|
|
3376
|
+
if (prior.integrity !== true) throw new ValidationError(`restore_doc: retained revision ${version} of ${doc_id} does not match its digest. Nothing was written.`, { code: 'EMET-DOC-043' });
|
|
3212
3377
|
const verdict = prior.conformance && prior.conformance.verdict;
|
|
3213
3378
|
const accepted = prior.conformance && prior.conformance.accepted;
|
|
3214
3379
|
if (!verdict) {
|
|
3215
|
-
if (templateFor(doc_id)) throw new ValidationError(`restore_doc: ${doc_id} is templated and the retained revision has no conformance verdict. Only an untemplated document can be restored without a verdict. Nothing was written
|
|
3380
|
+
if (templateFor(doc_id)) throw new ValidationError(`restore_doc: ${doc_id} is templated and the retained revision has no conformance verdict. Only an untemplated document can be restored without a verdict. Nothing was written.`, { code: 'EMET-DOC-044' });
|
|
3216
3381
|
} else if (verdict !== 'conforms' && verdict !== 'untemplated' && !accepted) {
|
|
3217
|
-
throw new ValidationError(`restore_doc: retained revision ${version} of ${doc_id} was not conforming. Nothing was written
|
|
3382
|
+
throw new ValidationError(`restore_doc: retained revision ${version} of ${doc_id} was not conforming. Nothing was written.`, { code: 'EMET-DOC-045' });
|
|
3218
3383
|
}
|
|
3219
3384
|
const current = await readDoc(doc_id, logger).catch(() => null);
|
|
3220
3385
|
const checked = validateDocument(doc_id, prior.content, current && current.content);
|
|
3221
3386
|
const lost = (checked.failures || []).filter((f) => /no disposition/.test(f));
|
|
3222
3387
|
if (doc_id === stateDoc() && (await unretiredBootDrops(options && options.session_id)).length) {
|
|
3223
|
-
throw new ValidationError('restore_doc: unhandled drops were listed at this session boot and must be retired with retire_doc before the board is restored. Nothing was written.');
|
|
3388
|
+
throw new ValidationError('restore_doc: unhandled drops were listed at this session boot and must be retired with retire_doc before the board is restored. Nothing was written.', { code: 'EMET-MEM-026' });
|
|
3224
3389
|
}
|
|
3225
3390
|
const written = await writeDoc(doc_id, prior.content, updated_by, null, logger, { restore_of: version, reason, session_id: options && options.session_id, supersedes: current && current.version });
|
|
3226
3391
|
return { ...written, rows_lost: lost, restored_from_version: version };
|
|
@@ -3241,7 +3406,7 @@ export async function validateDoc(options = {}, logger = null) {
|
|
|
3241
3406
|
if (!doc_id && !content) {
|
|
3242
3407
|
throw new ValidationError(
|
|
3243
3408
|
'Give a doc_id to check a stored document, or content (with template_id) to check text that is not stored yet.'
|
|
3244
|
-
);
|
|
3409
|
+
, { code: 'EMET-DOC-046' });
|
|
3245
3410
|
}
|
|
3246
3411
|
|
|
3247
3412
|
if (content) {
|
|
@@ -3251,7 +3416,7 @@ export async function validateDoc(options = {}, logger = null) {
|
|
|
3251
3416
|
failures: [], warnings: ['No template_id was given and no map entry matches, so nothing governs this content.'] };
|
|
3252
3417
|
}
|
|
3253
3418
|
const template = loadShipped(tpl_id);
|
|
3254
|
-
if (!template) throw new ValidationError(`No template ${tpl_id} ships with this release
|
|
3419
|
+
if (!template) throw new ValidationError(`No template ${tpl_id} ships with this release.`, { code: 'EMET-DOC-047' });
|
|
3255
3420
|
const r = checkRecord(content, template, { doc_id });
|
|
3256
3421
|
return { checked: doc_id || '(content)', template: tpl_id, template_status: template.status,
|
|
3257
3422
|
verdict: r.failures.length ? CONFORMANCE_VERDICT.NONCONFORMING : CONFORMANCE_VERDICT.CONFORMS,
|
|
@@ -3262,7 +3427,7 @@ export async function validateDoc(options = {}, logger = null) {
|
|
|
3262
3427
|
const { client, col, hist } = await _docsClient();
|
|
3263
3428
|
try {
|
|
3264
3429
|
const doc = await col.findOne({ doc_id });
|
|
3265
|
-
if (!doc) throw new ValidationError(`Document not found: ${doc_id}
|
|
3430
|
+
if (!doc) throw new ValidationError(`Document not found: ${doc_id}`, { code: 'EMET-DOC-002' });
|
|
3266
3431
|
// The carry-forward check needs the revision before this one, which is
|
|
3267
3432
|
// exactly what the history collection archived when this one was written.
|
|
3268
3433
|
const prior = await hist.find({ doc_id }).sort({ version: -1 }).limit(1).toArray();
|
|
@@ -3277,7 +3442,7 @@ export async function validateDoc(options = {}, logger = null) {
|
|
|
3277
3442
|
} finally { await client.close(); }
|
|
3278
3443
|
} catch (error) {
|
|
3279
3444
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
3280
|
-
throw new DatabaseError(`Failed to validate document: ${error.message}`, 'validate_doc');
|
|
3445
|
+
throw new DatabaseError(`Failed to validate document: ${error.message}`, 'validate_doc', { code: 'EMET-DB-031' });
|
|
3281
3446
|
}
|
|
3282
3447
|
}
|
|
3283
3448
|
|
|
@@ -3289,24 +3454,30 @@ export async function validateDoc(options = {}, logger = null) {
|
|
|
3289
3454
|
*/
|
|
3290
3455
|
export async function acceptNonconformance(doc_id, reason, accepted_by = null, logger = null, options = {}) {
|
|
3291
3456
|
try {
|
|
3457
|
+
if (typeof doc_id === 'string' && doc_id.startsWith('areas/')) {
|
|
3458
|
+
const { assertAreaOwner } = await import('./pages.js');
|
|
3459
|
+
const opened = await _docsClient();
|
|
3460
|
+
try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'accept_nonconformance'); }
|
|
3461
|
+
finally { await opened.client.close(); }
|
|
3462
|
+
}
|
|
3292
3463
|
refuseBotMainRecord(doc_id, accepted_by, 'accept_nonconformance');
|
|
3293
|
-
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
|
|
3464
|
+
if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
|
|
3294
3465
|
if (typeof reason !== 'string' || reason.trim().length < 10) {
|
|
3295
3466
|
throw new ValidationError(
|
|
3296
3467
|
'An acceptance needs a written reason of at least 10 characters. It is the disposition of ' +
|
|
3297
3468
|
'record for a nonconformance and is what an audit reads later - the same rule revise_transcript uses.'
|
|
3298
|
-
);
|
|
3469
|
+
, { code: 'EMET-DOC-048' });
|
|
3299
3470
|
}
|
|
3300
3471
|
const { client, col } = await _docsClient();
|
|
3301
3472
|
try {
|
|
3302
3473
|
const doc = await col.findOne({ doc_id });
|
|
3303
|
-
if (!doc) throw new ValidationError(`Document not found: ${doc_id}
|
|
3474
|
+
if (!doc) throw new ValidationError(`Document not found: ${doc_id}`, { code: 'EMET-DOC-002' });
|
|
3304
3475
|
const current = doc.conformance;
|
|
3305
3476
|
if (!current || current.verdict !== CONFORMANCE_VERDICT.NONCONFORMING) {
|
|
3306
3477
|
throw new ValidationError(
|
|
3307
3478
|
`${doc_id} version ${doc.version} carries no nonconformance marker, so there is nothing to accept. ` +
|
|
3308
3479
|
`Its verdict is "${current ? current.verdict : 'not yet checked'}".`
|
|
3309
|
-
);
|
|
3480
|
+
, { code: 'EMET-DOC-050' });
|
|
3310
3481
|
}
|
|
3311
3482
|
const { currentPersonId, currentClientId } = await import('./persons.js');
|
|
3312
3483
|
const accepted = buildAcceptance({
|
|
@@ -3320,7 +3491,7 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
|
|
|
3320
3491
|
const check = await col.findOne({ doc_id });
|
|
3321
3492
|
const stored = check && check.conformance && check.conformance.accepted;
|
|
3322
3493
|
if (!stored || stored.reason !== accepted.reason || Number(stored.covers_version) !== Number(doc.version)) {
|
|
3323
|
-
throw new DatabaseError(`The acceptance did not persist on ${doc_id}.`, 'accept_nonconformance');
|
|
3494
|
+
throw new DatabaseError(`The acceptance did not persist on ${doc_id}.`, 'accept_nonconformance', { code: 'EMET-DB-032' });
|
|
3324
3495
|
}
|
|
3325
3496
|
return {
|
|
3326
3497
|
doc_id, verified: true, version: doc.version, covers_version: doc.version,
|
|
@@ -3330,7 +3501,7 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
|
|
|
3330
3501
|
} finally { await client.close(); }
|
|
3331
3502
|
} catch (error) {
|
|
3332
3503
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
3333
|
-
throw new DatabaseError(`Failed to accept nonconformance: ${error.message}`, 'accept_nonconformance');
|
|
3504
|
+
throw new DatabaseError(`Failed to accept nonconformance: ${error.message}`, 'accept_nonconformance', { code: 'EMET-DB-033' });
|
|
3334
3505
|
}
|
|
3335
3506
|
}
|
|
3336
3507
|
|
|
@@ -3345,7 +3516,7 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
|
|
|
3345
3516
|
|
|
3346
3517
|
function _assertStr(v, name) {
|
|
3347
3518
|
if (typeof v !== 'string' || v.length === 0) {
|
|
3348
|
-
throw new ValidationError(`${name} must be a non-empty string
|
|
3519
|
+
throw new ValidationError(`${name} must be a non-empty string`, { code: 'EMET-DOC-051' });
|
|
3349
3520
|
}
|
|
3350
3521
|
}
|
|
3351
3522
|
|
|
@@ -3354,7 +3525,7 @@ function _assertVersion(cur, expected_version, tool) {
|
|
|
3354
3525
|
if (cur.version !== expected_version) {
|
|
3355
3526
|
throw new ValidationError(
|
|
3356
3527
|
`${tool}: version conflict - document is at v${cur.version}, caller expected v${expected_version}. Re-read and retry.`
|
|
3357
|
-
);
|
|
3528
|
+
, { code: 'EMET-DOC-052' });
|
|
3358
3529
|
}
|
|
3359
3530
|
}
|
|
3360
3531
|
|
|
@@ -3362,11 +3533,11 @@ function _assertVersion(cur, expected_version, tool) {
|
|
|
3362
3533
|
function _splitUnique(hay, needle, tool, what, doc_id) {
|
|
3363
3534
|
const parts = hay.split(needle);
|
|
3364
3535
|
const n = parts.length - 1;
|
|
3365
|
-
if (n === 0) throw new ValidationError(`${tool}: ${what} not found in ${doc_id}
|
|
3536
|
+
if (n === 0) throw new ValidationError(`${tool}: ${what} not found in ${doc_id}`, { code: 'EMET-DOC-053' });
|
|
3366
3537
|
if (n > 1) {
|
|
3367
3538
|
throw new ValidationError(
|
|
3368
3539
|
`${tool}: ${what} matches ${n} times in ${doc_id} - must match exactly once. Add surrounding context to disambiguate.`
|
|
3369
|
-
);
|
|
3540
|
+
, { code: 'EMET-DOC-054' });
|
|
3370
3541
|
}
|
|
3371
3542
|
return [parts[0], parts[1]];
|
|
3372
3543
|
}
|
|
@@ -3379,17 +3550,17 @@ export async function patchDoc(doc_id, old_str, new_str, updated_by = null, expe
|
|
|
3379
3550
|
if (!(Array.isArray(options.edits) && options.edits.length)) _assertStr(old_str, 'old_str');
|
|
3380
3551
|
const reason = options && options.reason;
|
|
3381
3552
|
if (typeof reason !== 'string' || reason.trim().length < 10) {
|
|
3382
|
-
throw new ValidationError('patch_doc needs reason (at least 10 characters). Nothing was written.');
|
|
3553
|
+
throw new ValidationError('patch_doc needs reason (at least 10 characters). Nothing was written.', { code: 'EMET-DOC-055' });
|
|
3383
3554
|
}
|
|
3384
3555
|
const cur = await readDoc(doc_id, logger);
|
|
3385
3556
|
_assertVersion(cur, expected_version, 'patch_doc');
|
|
3386
|
-
if (isDropDoc(doc_id)) throw new ValidationError('patch_doc: a drop is write-once. Use a new id. Nothing was written.');
|
|
3557
|
+
if (isDropDoc(doc_id)) throw new ValidationError('patch_doc: a drop is write-once. Use a new id. Nothing was written.', { code: 'EMET-DOC-056' });
|
|
3387
3558
|
const edits = Array.isArray(options.edits) && options.edits.length
|
|
3388
3559
|
? options.edits
|
|
3389
3560
|
: [{ old_str, new_str }];
|
|
3390
3561
|
for (const edit of edits) {
|
|
3391
|
-
if (typeof edit.old_str !== 'string' || edit.old_str.length === 0) throw new ValidationError('old_str must be a non-empty string');
|
|
3392
|
-
if (typeof edit.new_str !== 'string') throw new ValidationError('new_str must be a string (empty string allowed = delete)');
|
|
3562
|
+
if (typeof edit.old_str !== 'string' || edit.old_str.length === 0) throw new ValidationError('old_str must be a non-empty string', { code: 'EMET-DOC-057' });
|
|
3563
|
+
if (typeof edit.new_str !== 'string') throw new ValidationError('new_str must be a string (empty string allowed = delete)', { code: 'EMET-DOC-058' });
|
|
3393
3564
|
_splitUnique(cur.content, edit.old_str, 'patch_doc', 'old_str', doc_id);
|
|
3394
3565
|
}
|
|
3395
3566
|
const spans = edits.map((edit) => {
|
|
@@ -3398,18 +3569,18 @@ export async function patchDoc(doc_id, old_str, new_str, updated_by = null, expe
|
|
|
3398
3569
|
});
|
|
3399
3570
|
const ordered = [...spans].sort((a, b) => a.at - b.at);
|
|
3400
3571
|
for (let i = 1; i < ordered.length; i++) {
|
|
3401
|
-
if (ordered[i].at < ordered[i - 1].at + ordered[i - 1].len) throw new ValidationError('patch_doc: edits overlap. Nothing was written.');
|
|
3572
|
+
if (ordered[i].at < ordered[i - 1].at + ordered[i - 1].len) throw new ValidationError('patch_doc: edits overlap. Nothing was written.', { code: 'EMET-DOC-059' });
|
|
3402
3573
|
}
|
|
3403
3574
|
let next = cur.content;
|
|
3404
3575
|
for (const span of [...spans].sort((a, b) => b.at - a.at)) next = next.slice(0, span.at) + span.new_str + next.slice(span.at + span.len);
|
|
3405
3576
|
if (doc_id === stateDoc()) {
|
|
3406
|
-
if ((await unretiredBootDrops(options && options.session_id)).length) throw new ValidationError('patch_doc: unhandled drops were listed at this session boot and must be retired with retire_doc before the board is edited. Nothing was written.');
|
|
3577
|
+
if ((await unretiredBootDrops(options && options.session_id)).length) throw new ValidationError('patch_doc: unhandled drops were listed at this session boot and must be retired with retire_doc before the board is edited. Nothing was written.', { code: 'EMET-MEM-027' });
|
|
3407
3578
|
const ids = (text) => new Set([...String(text || '').matchAll(/\bB-\d+\b/g)].map((m) => m[0]));
|
|
3408
3579
|
const added = [...ids(next)].filter((id) => !ids(cur.content).has(id));
|
|
3409
|
-
if (added.length && !(options && options.origin)) throw new ValidationError('patch_doc: an added board row needs origin. Nothing was written.');
|
|
3580
|
+
if (added.length && !(options && options.origin)) throw new ValidationError('patch_doc: an added board row needs origin. Nothing was written.', { code: 'EMET-MEM-028' });
|
|
3410
3581
|
const checked = validateDocument(doc_id, next, cur.content);
|
|
3411
3582
|
if (checked && checked.verdict === 'nonconforming') {
|
|
3412
|
-
throw new ValidationError(`patch_doc: the board edit is nonconforming. ${(checked.failures || []).join('; ')} Nothing was written
|
|
3583
|
+
throw new ValidationError(`patch_doc: the board edit is nonconforming. ${(checked.failures || []).join('; ')} Nothing was written.`, { code: 'EMET-MEM-029' });
|
|
3413
3584
|
}
|
|
3414
3585
|
}
|
|
3415
3586
|
const res = await writeDoc(doc_id, next, updated_by, null, logger, { edited: true, reason, origin: options.origin || null, session_id: options.session_id || null });
|
|
@@ -3417,7 +3588,7 @@ export async function patchDoc(doc_id, old_str, new_str, updated_by = null, expe
|
|
|
3417
3588
|
size_delta: next.length - cur.content.length };
|
|
3418
3589
|
} catch (error) {
|
|
3419
3590
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
3420
|
-
throw new DatabaseError(`Failed to patch document: ${error.message}`, 'patch_doc');
|
|
3591
|
+
throw new DatabaseError(`Failed to patch document: ${error.message}`, 'patch_doc', { code: 'EMET-DB-034' });
|
|
3421
3592
|
}
|
|
3422
3593
|
}
|
|
3423
3594
|
|
|
@@ -3430,10 +3601,10 @@ const SEMANTIC_RECALL_INDEX = process.env.EMET_VECTOR_INDEX || 'emet_content_aut
|
|
|
3430
3601
|
export async function semanticRecall(query, layer = null, limit = 10, logger = null, options = null, dbManager = null) {
|
|
3431
3602
|
try {
|
|
3432
3603
|
if (!query || typeof query !== 'string' || query.trim() === '') {
|
|
3433
|
-
throw new ValidationError('query', 'query must be a non-empty string');
|
|
3604
|
+
throw new ValidationError('query', 'query must be a non-empty string', { code: 'EMET-MEM-030' });
|
|
3434
3605
|
}
|
|
3435
3606
|
if (query.length > CONTENT_LIMITS.MAX_QUERY_LENGTH) {
|
|
3436
|
-
throw new ValidationError('query', `query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}
|
|
3607
|
+
throw new ValidationError('query', `query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`, { code: 'EMET-VAL-008' });
|
|
3437
3608
|
}
|
|
3438
3609
|
const validatedLimit = validateLimit(limit);
|
|
3439
3610
|
const layers = layer ? [validateLayer(layer)] : SEMANTIC_RECALL_LAYERS;
|
|
@@ -3494,7 +3665,7 @@ export async function semanticRecall(query, layer = null, limit = 10, logger = n
|
|
|
3494
3665
|
} finally { if (client) await client.close(); }
|
|
3495
3666
|
} catch (error) {
|
|
3496
3667
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
3497
|
-
throw new DatabaseError(`Failed semantic recall: ${error.message}`, 'semantic_recall');
|
|
3668
|
+
throw new DatabaseError(`Failed semantic recall: ${error.message}`, 'semantic_recall', { code: 'EMET-DB-035' });
|
|
3498
3669
|
}
|
|
3499
3670
|
}
|
|
3500
3671
|
|
|
@@ -3521,15 +3692,15 @@ const CORPUS_VALUES = (process.env.EMET_CORPORA || '').split(',').map(s => s.tri
|
|
|
3521
3692
|
export async function corpusRecall(query, corpus = null, limit = 5, logger = null) {
|
|
3522
3693
|
try {
|
|
3523
3694
|
if (!query || typeof query !== 'string' || query.trim() === '') {
|
|
3524
|
-
throw new ValidationError('query', 'query must be a non-empty string');
|
|
3695
|
+
throw new ValidationError('query', 'query must be a non-empty string', { code: 'EMET-MEM-030' });
|
|
3525
3696
|
}
|
|
3526
3697
|
if (query.length > CONTENT_LIMITS.MAX_QUERY_LENGTH) {
|
|
3527
|
-
throw new ValidationError('query', `query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}
|
|
3698
|
+
throw new ValidationError('query', `query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`, { code: 'EMET-VAL-008' });
|
|
3528
3699
|
}
|
|
3529
3700
|
const validatedLimit = Math.min(Math.max(parseInt(limit) || 5, 1), 25);
|
|
3530
3701
|
// An empty EMET_CORPORA means "unrestricted", not "nothing allowed".
|
|
3531
3702
|
if (corpus && CORPUS_VALUES.length && !CORPUS_VALUES.includes(corpus)) {
|
|
3532
|
-
throw new ValidationError('corpus', `corpus must be one of: ${CORPUS_VALUES.join(', ')}
|
|
3703
|
+
throw new ValidationError('corpus', `corpus must be one of: ${CORPUS_VALUES.join(', ')}`, { code: 'EMET-MEM-032' });
|
|
3533
3704
|
}
|
|
3534
3705
|
const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 5000, maxPoolSize: 10 });
|
|
3535
3706
|
try {
|
|
@@ -3574,7 +3745,7 @@ export async function corpusRecall(query, corpus = null, limit = 5, logger = nul
|
|
|
3574
3745
|
} finally { await client.close(); }
|
|
3575
3746
|
} catch (error) {
|
|
3576
3747
|
if (error instanceof ValidationError || error instanceof EmetError) throw error;
|
|
3577
|
-
throw new DatabaseError(`Failed corpus recall: ${error.message}`, 'corpus_recall');
|
|
3748
|
+
throw new DatabaseError(`Failed corpus recall: ${error.message}`, 'corpus_recall', { code: 'EMET-DB-036' });
|
|
3578
3749
|
}
|
|
3579
3750
|
}
|
|
3580
3751
|
|
|
@@ -3605,35 +3776,36 @@ export {
|
|
|
3605
3776
|
* and is the owner. HTTP still requires a loaded person whose role is owner.
|
|
3606
3777
|
* An in-process actor that names a person is checked the same way.
|
|
3607
3778
|
*/
|
|
3608
|
-
async function codeCreator(dbManager
|
|
3779
|
+
async function codeCreator(dbManager) {
|
|
3609
3780
|
const { currentActor, getPerson } = await import('./persons.js');
|
|
3610
3781
|
const actor = currentActor();
|
|
3611
3782
|
if (actor.transport === 'stdio' || (actor.transport !== 'http' && !actor.personId)) {
|
|
3612
3783
|
return actor.personId || LOCAL_SUBJECT;
|
|
3613
3784
|
}
|
|
3614
|
-
if (!actor.personId)
|
|
3785
|
+
if (!actor.personId) return null;
|
|
3615
3786
|
const person = await getPerson(dbManager.db, actor.personId);
|
|
3616
|
-
if (!person || person.role !== 'owner')
|
|
3787
|
+
if (!person || person.role !== 'owner') return null;
|
|
3617
3788
|
return actor.personId;
|
|
3618
3789
|
}
|
|
3619
3790
|
|
|
3620
3791
|
export async function inviteCreate(dbManager, { display_name, scopes, days, source } = {}, logger = null) {
|
|
3621
3792
|
if (!display_name || !String(display_name).trim()) {
|
|
3622
|
-
throw new ValidationError('display_name is required — the name the guest will be known by');
|
|
3793
|
+
throw new ValidationError('display_name is required — the name the guest will be known by', { code: 'EMET-AUTH-029' });
|
|
3623
3794
|
}
|
|
3624
3795
|
await dbManager.getConnection('working');
|
|
3625
3796
|
const { createInvite, INVITES_FROZEN, INVITES_FROZEN_REASON } = await import('./invites.js');
|
|
3626
|
-
if (INVITES_FROZEN) throw new ValidationError(INVITES_FROZEN_REASON);
|
|
3797
|
+
if (INVITES_FROZEN) throw new ValidationError(INVITES_FROZEN_REASON, { code: 'EMET-AUTH-030' });
|
|
3627
3798
|
const { registeredSourceTags } = await import('./setup.js');
|
|
3628
|
-
const actor = await codeCreator(dbManager
|
|
3799
|
+
const actor = await codeCreator(dbManager);
|
|
3800
|
+
if (!actor) throw new ValidationError('Only the owner can create invites', { code: 'EMET-AUTH-036' });
|
|
3629
3801
|
const requested = Array.isArray(scopes) ? scopes : ['emet.read'];
|
|
3630
3802
|
if (requested.length !== 1 || requested[0] !== 'emet.read') {
|
|
3631
|
-
throw new ValidationError('A guest invite accepts only emet.read');
|
|
3803
|
+
throw new ValidationError('A guest invite accepts only emet.read', { code: 'EMET-AUTH-031' });
|
|
3632
3804
|
}
|
|
3633
3805
|
const registry = registeredSourceTags();
|
|
3634
3806
|
const tag = typeof source === 'string' ? source.trim() : '';
|
|
3635
3807
|
if (registry.length && tag && !registry.includes(tag)) {
|
|
3636
|
-
throw new ValidationError('source', 'A guest invite source must be a registered tag. Nothing was created.');
|
|
3808
|
+
throw new ValidationError('source', 'A guest invite source must be a registered tag. Nothing was created.', { code: 'EMET-AUTH-032' });
|
|
3637
3809
|
}
|
|
3638
3810
|
const out = await createInvite(dbManager.db, {
|
|
3639
3811
|
created_by: actor,
|
|
@@ -3651,17 +3823,18 @@ export async function inviteCreate(dbManager, { display_name, scopes, days, sour
|
|
|
3651
3823
|
|
|
3652
3824
|
export async function memberAccessCreate(dbManager, { display_name, days, source } = {}, logger = null) {
|
|
3653
3825
|
if (!display_name || !String(display_name).trim()) {
|
|
3654
|
-
throw new ValidationError('display_name is required \u2014 the name the member will be known by');
|
|
3826
|
+
throw new ValidationError('display_name is required \u2014 the name the member will be known by', { code: 'EMET-AUTH-033' });
|
|
3655
3827
|
}
|
|
3656
3828
|
await dbManager.getConnection('working');
|
|
3657
3829
|
const { createMemberAccess, MEMBER_ACCESS_FROZEN, MEMBER_ACCESS_FROZEN_REASON } = await import('./invites.js');
|
|
3658
|
-
if (MEMBER_ACCESS_FROZEN) throw new ValidationError(MEMBER_ACCESS_FROZEN_REASON);
|
|
3830
|
+
if (MEMBER_ACCESS_FROZEN) throw new ValidationError(MEMBER_ACCESS_FROZEN_REASON, { code: 'EMET-AUTH-034' });
|
|
3659
3831
|
const { registeredSourceTags } = await import('./setup.js');
|
|
3660
|
-
const actor = await codeCreator(dbManager
|
|
3832
|
+
const actor = await codeCreator(dbManager);
|
|
3833
|
+
if (!actor) throw new ValidationError('Only the owner can create EMET Member Access', { code: 'EMET-AUTH-037' });
|
|
3661
3834
|
const registry = registeredSourceTags();
|
|
3662
3835
|
const tag = typeof source === 'string' ? source.trim() : '';
|
|
3663
3836
|
if (registry.length && tag && !registry.includes(tag)) {
|
|
3664
|
-
throw new ValidationError('source', 'A member code source must be a registered tag. Nothing was created.');
|
|
3837
|
+
throw new ValidationError('source', 'A member code source must be a registered tag. Nothing was created.', { code: 'EMET-AUTH-035' });
|
|
3665
3838
|
}
|
|
3666
3839
|
const out = await createMemberAccess(dbManager.db, { created_by: actor, display_name, days: days || 14, source_tag: tag || null });
|
|
3667
3840
|
logger?.info?.('EMET Member Access created', { display_name: out.display_name });
|
|
@@ -3682,7 +3855,8 @@ const TOOL_DEFINITIONS = [
|
|
|
3682
3855
|
properties: {
|
|
3683
3856
|
recent_limit: { type: "number", description: "How many recent context entries to return (default 5)." },
|
|
3684
3857
|
page: { description: "The startup is served in pages when it is larger than one result (each page fits under 20,000 bytes). Omit for page 1; every page but the last says which page to ask for next - call again with that page, before replying, until a page says it is the last. \"all\" returns the whole startup in one result, for a host with no size limit." },
|
|
3685
|
-
load_id: { type: "string", description: "The load_id your startup returned in `startup_page.load_id`: every emet_initialize result carries one (each page of a paged startup, the whole startup with page \"all\" or when it fits one result, and a store that is not set up yet). Pass it with every later page so all pages come from the same startup, and pass the same load_id to emet_session_open so its startup page check runs on this startup." }
|
|
3858
|
+
load_id: { type: "string", description: "The load_id your startup returned in `startup_page.load_id`: every emet_initialize result carries one (each page of a paged startup, the whole startup with page \"all\" or when it fits one result, and a store that is not set up yet). Pass it with every later page so all pages come from the same startup, and pass the same load_id to emet_session_open so its startup page check runs on this startup." },
|
|
3859
|
+
source: { type: "string", description: "Your own source tag (the bot or host you are). The startup then reports the tag your writes will carry and its approval state." }
|
|
3686
3860
|
}
|
|
3687
3861
|
}
|
|
3688
3862
|
},
|
|
@@ -3692,13 +3866,14 @@ const TOOL_DEFINITIONS = [
|
|
|
3692
3866
|
inputSchema: {
|
|
3693
3867
|
type: "object",
|
|
3694
3868
|
properties: {
|
|
3695
|
-
probe: { type: "boolean", description: "Also write and read back a probe document (default false). Use after a deploy or a configuration change." }
|
|
3869
|
+
probe: { type: "boolean", description: "Also write and read back a probe document (default false). Use after a deploy or a configuration change." },
|
|
3870
|
+
source: { type: "string", description: "Your own source tag. The status then reports the tag your writes will carry and its approval state." }
|
|
3696
3871
|
}
|
|
3697
3872
|
}
|
|
3698
3873
|
},
|
|
3699
3874
|
{
|
|
3700
3875
|
name: "emet_setup_complete",
|
|
3701
|
-
description: "First-time setup, the owner's only: record the user's interview answers as bootstrap/IDENTITY.md, bootstrap/CHARACTER.md and bootstrap/USER.md and as an identity-layer entry, and create the owner person. Every write is read-back verified. Refused under a bot tag. On a store that is already set up it is refused unless reissue is true (the owner's explicit word): a re-run writes new versions of the user's identity documents; prior versions are archived, never destroyed.",
|
|
3876
|
+
description: "First-time setup, the owner's only: record the user's interview answers as bootstrap/IDENTITY.md, bootstrap/CHARACTER.md and bootstrap/USER.md and as an identity-layer entry, and create the owner person. Every write is read-back verified. Refused under a bot tag. On a store that is already set up it is refused unless reissue is true (the owner's explicit word): a re-run writes new versions of the user's identity documents; prior versions are archived, never destroyed. answers.more_than_one_bot is optional. Absent or no leaves sub-keys off. yes writes EMET_SUBKEYS=1, a generated pepper and EMET_SUBKEY_PEPPER_VERSION=1 into .env only when that file is the config source, after the store writes succeed, and does not turn the flag on in this process. A hosted server refuses yes and returns the three variables to set, then redeploy. See docs/SUBKEYS.md. answers.bot_team_backup is optional. Yes or no, in the user's words, the same way as more_than_one_bot. Yes and Yes. record the flag. yes is the recommended choice. Absent or no leaves bot-team backup off. Anything else, including a non-string, is refused before a write. Setup does not copy prompts or settings.",
|
|
3702
3877
|
inputSchema: {
|
|
3703
3878
|
type: "object",
|
|
3704
3879
|
properties: {
|
|
@@ -3711,7 +3886,9 @@ const TOOL_DEFINITIONS = [
|
|
|
3711
3886
|
user_name: { type: "string" },
|
|
3712
3887
|
user_context: { type: "string" },
|
|
3713
3888
|
user_preferences: { type: "string" },
|
|
3714
|
-
source_tag: { type: "string" }
|
|
3889
|
+
source_tag: { type: "string" },
|
|
3890
|
+
more_than_one_bot: { type: "string", description: "Optional. yes or no, in the user's words. Absent or no leaves sub-keys off. yes turns them on only when this server reads .env. Do not invent this answer." },
|
|
3891
|
+
bot_team_backup: { type: "string", description: "Optional. Yes or no, in the user's words. Yes and Yes. count as yes. yes is the recommended choice and records bot-team backup as on. Absent or no leaves it off. A non-string is refused. Do not invent this answer." }
|
|
3715
3892
|
},
|
|
3716
3893
|
required: ["assistant_name", "assistant_character", "user_name", "user_context"]
|
|
3717
3894
|
},
|
|
@@ -4132,6 +4309,37 @@ const TOOL_DEFINITIONS = [
|
|
|
4132
4309
|
history: { type: "boolean", description: "Return ended entries only, up to limit. Default false: current matches come first and ended matches follow until limit, marked with their end date." }
|
|
4133
4310
|
}, required: ["query"] }
|
|
4134
4311
|
},
|
|
4312
|
+
{
|
|
4313
|
+
name: "emet_page",
|
|
4314
|
+
description: "Read one compiled topic page for an area slug (areas/<slug>.md). A page is a view of current records. It is not a record: this tool writes nothing, stores nothing, and the result is never written back and is not returned by recall. Every displayed line cites its source as [mem:<id> · <layer> · <client> · <YYYY-MM-DD>] or [doc:<doc_id>@v<version>]. A line with no source is dropped. Superseded and retired records stay out of the current sections; pass include_history true to show them under History only. A line is marked stale when its source has not been confirmed or revised within the area's staleness window (default 30 days; the area document may set its own). Owner only. Computed on every call, so cache_hit is false.",
|
|
4315
|
+
inputSchema: { type: "object", properties: {
|
|
4316
|
+
area: { type: "string", description: "Area slug, for example health. The selector is the current areas/<slug>.md document." },
|
|
4317
|
+
as_of: { type: "string", description: "Optional ISO date or unix seconds. The page shows records that were current at that moment. A document line cites the revision in force then, from documents_history. A revision that was never archived is absent. A superseded or retired record with no end date is still shown in this past view, labelled \"end date unknown\", and is not a current line. The area selector is the current area document." },
|
|
4318
|
+
include_history: { type: "boolean", description: "When true, superseded and retired records appear under History, labelled as not current. Default false." }
|
|
4319
|
+
}, required: ["area"] }
|
|
4320
|
+
},
|
|
4321
|
+
{
|
|
4322
|
+
name: "emet_pages",
|
|
4323
|
+
description: "List current area documents. For each area: line count, stale count, and the time of the newest source the page read. Read-only. Owner only. Computed on every call. The page body is not stored.",
|
|
4324
|
+
inputSchema: { type: "object", properties: {} }
|
|
4325
|
+
},
|
|
4326
|
+
{
|
|
4327
|
+
name: "emet_error_report",
|
|
4328
|
+
description: "Read the operational error log and show a report the owner can send on. Owner only. Read-only: it writes nothing and sends nothing. EMET has no mail sender and opens no network connection for this tool. The result is the full report, then a mailto link, then a structured email {to, subject, body_text, short_id, version} a calling assistant can pass to its own email tool. The calling assistant may send this report only after showing the report to its user and getting their OK.",
|
|
4329
|
+
inputSchema: { type: "object", properties: {
|
|
4330
|
+
since: { type: "string", description: "ISO date (YYYY-MM-DD) or UTC timestamp. Default is 7 days ago. Cannot be older than 90 days." },
|
|
4331
|
+
codes: { type: "array", items: { type: "string" }, description: "Optional list of EMET codes to include." },
|
|
4332
|
+
correlation_id: { type: "string", description: "16 hex characters from an error response. When set, since is ignored." },
|
|
4333
|
+
limit: { type: "number", description: "How many of the most recent entries to list. Default 50, maximum 200." }
|
|
4334
|
+
} }
|
|
4335
|
+
},
|
|
4336
|
+
{
|
|
4337
|
+
name: "emet_page_lint",
|
|
4338
|
+
description: "Flag problems in topic pages and the records they read. Read-only: it never edits a record. Findings cover contradictions (two current records that share a subject and disagree), superseded or retired records still claimed as current, lines with no source, duplicates, broken links, and statuses unconfirmed longer than the area's staleness window. It builds on the emet_gaps classifiers. A fix is a person's revise_memory, retire_doc, or accept_nonconformance. Owner only. Omit area to lint every area.",
|
|
4339
|
+
inputSchema: { type: "object", properties: {
|
|
4340
|
+
area: { type: "string", description: "Optional area slug. Omit to lint every current area." }
|
|
4341
|
+
} }
|
|
4342
|
+
},
|
|
4135
4343
|
{
|
|
4136
4344
|
name: "emet_gaps",
|
|
4137
4345
|
description: "The record's honesty about its own holes, as a query. Read-only; identifies and never fills. Counts, with the ids behind them, for each gap class: unsourced assertions, unattributed inferences, ambiguous attribution (by tag and by session), uncertain routing, unattestable rows (pre-2026-09-05 boundary), digest mismatches (the alarm - expect zero), pointer disagreements against the transcript store, broken supersession, expired-but-live rows, consolidation candidates (tag families; a list for a person), and redacted spans by source. Call it when asked how trustworthy the record is, before a consolidation pass, or after any migration. Closing a gap is a person's decision: revise_memory with a real derived_from where the source is knowable; otherwise the gap stands as a fact.",
|
|
@@ -4146,15 +4354,31 @@ const TOOL_DEFINITIONS = [
|
|
|
4146
4354
|
},
|
|
4147
4355
|
{
|
|
4148
4356
|
name: "emet_floor",
|
|
4149
|
-
description: "Read the floor: the standing description of how this assistant engages with the person using it. It ships in the server code, so setup cannot overwrite it and no install can lose it - the character document holds the user's modifiers on top of it. emet_initialize already returns the whole floor at session start; call this to read it again without re-running initialize. Use `compact: true` for the short form partway through a long session, when the start of the conversation is far behind. Read-only, and re-reading is not the same as being bound by it.",
|
|
4357
|
+
description: "Read the floor: the standing description of how this assistant engages with the person using it. It ships in the server code, so setup cannot overwrite it and no install can lose it - the character document holds the user's modifiers on top of it. emet_initialize already returns the whole floor at session start; call this to read it again without re-running initialize. Use `compact: true` for the short form partway through a long session, when the start of the conversation is far behind. Pass `gem` to read one installed GEM's floor; reading does not turn that GEM on. Read-only, and re-reading is not the same as being bound by it.",
|
|
4150
4358
|
inputSchema: {
|
|
4151
4359
|
type: "object",
|
|
4152
4360
|
properties: {
|
|
4153
4361
|
compact: { type: "boolean", description: "Return the short re-assertion form instead of the whole floor." },
|
|
4154
|
-
section: { type: "string", description: "Return one section only, e.g. '
|
|
4362
|
+
section: { type: "string", description: "Return one section only, e.g. 'voice'. Call with no arguments to see the section names." },
|
|
4363
|
+
gem: { type: "string", description: "Read one installed GEM's floor by id, for example 'neurendipity'. Reading does not turn the GEM on. Omit it to read the core floor." }
|
|
4155
4364
|
}
|
|
4156
4365
|
}
|
|
4157
4366
|
},
|
|
4367
|
+
{
|
|
4368
|
+
name: "emet_client_approve",
|
|
4369
|
+
description: "Approve or deny a new client (a bot, or a single-instance AI such as Claude or ChatGPT) that EMET flagged on its first write. A new client is read-limited until approved. Only the owner, or the chief-of-staff bot named by EMET_COS_TAG, may decide. Pending clients are listed in emet_initialize and emet_status as client_approvals.",
|
|
4370
|
+
inputSchema: {
|
|
4371
|
+
type: "object",
|
|
4372
|
+
properties: {
|
|
4373
|
+
tag: { type: "string", description: "The pending client's tag, as listed in client_approvals.pending" },
|
|
4374
|
+
decision: { type: "string", enum: ["approve", "deny"] },
|
|
4375
|
+
reason: { type: "string", description: "Optional note kept with the decision" },
|
|
4376
|
+
as: { type: "string", enum: ["rename", "add"], description: "Required when the client_id already has approved tags: add keeps them all (several bots on one shared client); rename retires one" },
|
|
4377
|
+
from: { type: "string", description: "With as=rename on a client that has several approved tags: the tag being replaced" }
|
|
4378
|
+
},
|
|
4379
|
+
required: ["tag", "decision"]
|
|
4380
|
+
}
|
|
4381
|
+
},
|
|
4158
4382
|
{
|
|
4159
4383
|
name: "emet_invite_create",
|
|
4160
4384
|
description: "EMET Guest Access: create a one-time code for a guest. They paste it on the connect screen instead of the passphrase. Default access is read-only. Only the owner can create a guest code. EMET Member Access is a different door.",
|
|
@@ -4212,6 +4436,43 @@ const TOOL_DEFINITIONS = [
|
|
|
4212
4436
|
}
|
|
4213
4437
|
];
|
|
4214
4438
|
|
|
4439
|
+
/** Registered only when EMET_SUBKEYS=1. Flag off, a host's tool list does not include them. */
|
|
4440
|
+
const SUBKEY_TOOL_DEFINITIONS = [
|
|
4441
|
+
{
|
|
4442
|
+
name: "emet_subkey_request",
|
|
4443
|
+
description: "Request a delegated client sub-key for one registered source tag. Only an authenticated HTTP login of the owner may call it, and only when EMET_SUBKEYS=1. The result carries a one-time claim nonce. The server stores only its HMAC. Approve or deny the request with emet_client_approve from the owner's own login.",
|
|
4444
|
+
inputSchema: { type: "object", properties: {
|
|
4445
|
+
tag: { type: "string", description: "The source tag this key will stamp. An exact member of EMET_SOURCE_TAGS when a registry is set." }
|
|
4446
|
+
}, required: ["tag"] }
|
|
4447
|
+
},
|
|
4448
|
+
{
|
|
4449
|
+
name: "emet_subkey_claim",
|
|
4450
|
+
description: "Claim an approved sub-key with the key_id and the one-time nonce from emet_subkey_request. The result carries the emk_ key once. A second claim, a wrong nonce, or a missing pepper is refused. The bot keeps the key as a local secret; it is never written into EMET content.",
|
|
4451
|
+
inputSchema: { type: "object", properties: {
|
|
4452
|
+
key_id: { type: "string", description: "The key_id from emet_subkey_request." },
|
|
4453
|
+
nonce: { type: "string", description: "The one-time emn_ nonce from emet_subkey_request." }
|
|
4454
|
+
}, required: ["key_id", "nonce"] }
|
|
4455
|
+
},
|
|
4456
|
+
{
|
|
4457
|
+
name: "emet_subkey_revoke",
|
|
4458
|
+
description: "Revoke a client sub-key by tag or key_id. The owner's own login can always revoke. The key record is kept. A later write with its session handle is refused, and earlier writes stay as written.",
|
|
4459
|
+
inputSchema: { type: "object", properties: {
|
|
4460
|
+
tag: { type: "string", description: "Revoke the live key for this tag. Pass tag or key_id." },
|
|
4461
|
+
key_id: { type: "string", description: "Revoke this key. Pass tag or key_id." },
|
|
4462
|
+
reason: { type: "string", description: "Why it was revoked. Kept on the record." }
|
|
4463
|
+
} }
|
|
4464
|
+
},
|
|
4465
|
+
{
|
|
4466
|
+
name: "emet_subkey_end_session",
|
|
4467
|
+
description: "End a sub-key's live session without revoking the key. Owner only. Use it when the single live session is stuck and the key should stay usable. The old session handle stops working; the bot opens a new session with the same key.",
|
|
4468
|
+
inputSchema: { type: "object", properties: {
|
|
4469
|
+
tag: { type: "string", description: "The tag whose live session to end. Pass tag or key_id." },
|
|
4470
|
+
key_id: { type: "string", description: "The key whose live session to end. Pass tag or key_id." },
|
|
4471
|
+
reason: { type: "string", description: "Why the session was ended. Kept on the record." }
|
|
4472
|
+
} }
|
|
4473
|
+
}
|
|
4474
|
+
];
|
|
4475
|
+
|
|
4215
4476
|
/**
|
|
4216
4477
|
* The tool list as hosts receive it, with MCP annotations attached.
|
|
4217
4478
|
*
|
|
@@ -4220,7 +4481,7 @@ const TOOL_DEFINITIONS = [
|
|
|
4220
4481
|
* acting, exactly as risky as an arbitrary shell command.
|
|
4221
4482
|
*/
|
|
4222
4483
|
/**
|
|
4223
|
-
* The session graph's two inputs on every write tool (2026-09-29):
|
|
4484
|
+
* The session graph's two inputs on every write tool (2026-09-29, board 120):
|
|
4224
4485
|
* `session_id` names the session the write belongs to, `exchange` the turn.
|
|
4225
4486
|
* Added here, once, rather than hand-copied into each schema; a schema that
|
|
4226
4487
|
* already declares one keeps its own description.
|
|
@@ -4236,8 +4497,61 @@ for (const t of TOOL_DEFINITIONS) {
|
|
|
4236
4497
|
t.inputSchema.properties = t.inputSchema.properties || {};
|
|
4237
4498
|
for (const [k, v] of Object.entries(GRAPH_INPUTS)) if (!t.inputSchema.properties[k]) t.inputSchema.properties[k] = v;
|
|
4238
4499
|
}
|
|
4500
|
+
const SESSION_HANDLE_INPUT = {
|
|
4501
|
+
type: 'string',
|
|
4502
|
+
description: 'Required on every write in a session opened with a sub-key. The session_handle emet_session_open returned once. It is not repeated in receipts, logs, or session_graph.'
|
|
4503
|
+
};
|
|
4504
|
+
const SUBKEY_OPEN_INPUT = {
|
|
4505
|
+
type: 'string',
|
|
4506
|
+
description: 'The bot\'s emk_ sub-key. Presented once here. The result\'s session_handle is what later writes in this session pass.'
|
|
4507
|
+
};
|
|
4508
|
+
const SUBKEY_CLOSE_INPUT = {
|
|
4509
|
+
type: 'string',
|
|
4510
|
+
description: 'The emk_ sub-key that opened this session. A close releases that sub-key session only when this and session_handle are the ones that opened it. The handle is checked against receipts.transcript_session_id.'
|
|
4511
|
+
};
|
|
4239
4512
|
|
|
4240
|
-
|
|
4513
|
+
function cloneTool(t) {
|
|
4514
|
+
const schema = t.inputSchema ? {
|
|
4515
|
+
...t.inputSchema,
|
|
4516
|
+
properties: { ...(t.inputSchema.properties || {}) },
|
|
4517
|
+
...(Array.isArray(t.inputSchema.required) ? { required: [...t.inputSchema.required] } : {})
|
|
4518
|
+
} : t.inputSchema;
|
|
4519
|
+
return { ...t, inputSchema: schema };
|
|
4520
|
+
}
|
|
4521
|
+
|
|
4522
|
+
let toolCache = { flag: null, tools: null };
|
|
4523
|
+
|
|
4524
|
+
/** The tool list a host receives. The four sub-key tools and their schema fields exist only when EMET_SUBKEYS=1. */
|
|
4525
|
+
export function hostTools() {
|
|
4526
|
+
const on = setting('SUBKEYS') === '1';
|
|
4527
|
+
if (toolCache.tools && toolCache.flag === on) return toolCache.tools;
|
|
4528
|
+
const defs = TOOL_DEFINITIONS.map(cloneTool);
|
|
4529
|
+
if (on) {
|
|
4530
|
+
const open = defs.find((t) => t.name === 'emet_session_open');
|
|
4531
|
+
if (open && open.inputSchema) open.inputSchema.properties.subkey = SUBKEY_OPEN_INPUT;
|
|
4532
|
+
const close = defs.find((t) => t.name === 'emet_session_close');
|
|
4533
|
+
if (close && close.inputSchema) close.inputSchema.properties.subkey = SUBKEY_CLOSE_INPUT;
|
|
4534
|
+
for (const t of defs) {
|
|
4535
|
+
const props = t.inputSchema && t.inputSchema.properties;
|
|
4536
|
+
if (!props || !props.session_id || props.session_handle) continue;
|
|
4537
|
+
props.session_handle = SESSION_HANDLE_INPUT;
|
|
4538
|
+
}
|
|
4539
|
+
defs.push(...SUBKEY_TOOL_DEFINITIONS.map(cloneTool));
|
|
4540
|
+
}
|
|
4541
|
+
const tools = annotate(defs);
|
|
4542
|
+
toolCache = { flag: on, tools };
|
|
4543
|
+
return tools;
|
|
4544
|
+
}
|
|
4545
|
+
|
|
4546
|
+
/** Live view of hostTools(), so a test that flips EMET_SUBKEYS sees the list for that flag. */
|
|
4547
|
+
export const TOOLS = new Proxy([], {
|
|
4548
|
+
get(_target, prop) {
|
|
4549
|
+
const list = hostTools();
|
|
4550
|
+
if (prop === Symbol.iterator) return list[Symbol.iterator].bind(list);
|
|
4551
|
+
const value = list[prop];
|
|
4552
|
+
return typeof value === 'function' ? value.bind(list) : value;
|
|
4553
|
+
}
|
|
4554
|
+
});
|
|
4241
4555
|
|
|
4242
4556
|
|
|
4243
4557
|
// ============================================
|