@remnic/core 9.69.54 → 9.69.56
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/dist/access-admin-ops-surface.d.ts +1 -1
- package/dist/access-admin-ops-surface.js +2 -2
- package/dist/access-authorization-probe.d.ts +1 -1
- package/dist/access-authorization-probe.js +3 -3
- package/dist/access-boundary.d.ts +1 -1
- package/dist/access-boundary.js +2 -2
- package/dist/access-cli.js +24 -24
- package/dist/access-extraction-force-flush.d.ts +1 -1
- package/dist/access-extraction-force-flush.js +2 -2
- package/dist/access-http-briefing.d.ts +1 -1
- package/dist/access-http-briefing.js +3 -3
- package/dist/access-http-lcm-compaction.d.ts +1 -1
- package/dist/access-http-lifecycle-flush.d.ts +1 -1
- package/dist/access-http-offline-stream.d.ts +1 -1
- package/dist/access-http-query.js +2 -2
- package/dist/access-http.d.ts +2 -2
- package/dist/access-http.js +14 -14
- package/dist/access-identity-continuity-surface.js +2 -2
- package/dist/access-lcm-surface.d.ts +1 -1
- package/dist/access-lcm-surface.js +2 -2
- package/dist/access-mcp-shared-context-tools.d.ts +1 -1
- package/dist/access-mcp.d.ts +1 -1
- package/dist/access-mcp.js +9 -9
- package/dist/access-namespace-preflight.js +2 -2
- package/dist/access-observe-write-surface.d.ts +1 -1
- package/dist/access-observe-write-surface.js +2 -2
- package/dist/access-operations-batch.js +3 -3
- package/dist/access-operations.d.ts +1 -1
- package/dist/access-operations.js +8 -8
- package/dist/access-recall-concurrency.d.ts +1 -1
- package/dist/access-recall-concurrency.js +2 -2
- package/dist/access-recall-response.d.ts +1 -1
- package/dist/access-recall-response.js +2 -2
- package/dist/access-recall-surface.d.ts +1 -1
- package/dist/access-recall-surface.js +2 -2
- package/dist/access-schema.d.ts +113 -113
- package/dist/{access-service-H-qEdnSs.d.ts → access-service-CUNM5RfA.d.ts} +64 -64
- package/dist/access-service-helpers.d.ts +1 -1
- package/dist/access-service.d.ts +1 -1
- package/dist/access-service.js +2 -2
- package/dist/access-surface-catalog.d.ts +1 -1
- package/dist/access-surface-catalog.js +4 -4
- package/dist/active-recall.js +2 -2
- package/dist/{chunk-ZADYEZY4.js → chunk-2SIKTXWX.js} +2 -2
- package/dist/{chunk-ZHV6FGVF.js → chunk-3R23DDD3.js} +8 -8
- package/dist/{chunk-EQNZC3BH.js → chunk-3S6URXEH.js} +2 -2
- package/dist/{chunk-BCXZ4BDS.js → chunk-75YZ5VAI.js} +2 -2
- package/dist/{chunk-MXTCV3B5.js → chunk-AHVJ6GLL.js} +2 -2
- package/dist/{chunk-6UEM5EOB.js → chunk-AQ55YKEV.js} +2 -2
- package/dist/{chunk-VMKAA5SU.js → chunk-BSCNBIF4.js} +2 -2
- package/dist/{chunk-M7HFDWOS.js → chunk-FROKVQQY.js} +2 -2
- package/dist/{chunk-A4TQFNRX.js → chunk-GRDRVYXJ.js} +3 -3
- package/dist/{chunk-EYK3UHAP.js → chunk-H6WOFMOV.js} +2 -2
- package/dist/{chunk-SOOWBRMH.js → chunk-IYNCJKBM.js} +8 -8
- package/dist/{chunk-3KJTSCSX.js → chunk-J54B5DGD.js} +5 -4
- package/dist/chunk-J54B5DGD.js.map +1 -0
- package/dist/{chunk-KGY6F4VJ.js → chunk-KIGC55FQ.js} +2 -2
- package/dist/{chunk-KQQEZTH6.js → chunk-KQVBR7BC.js} +2 -2
- package/dist/{chunk-MTJUIIM4.js → chunk-MTWD4KMM.js} +2 -2
- package/dist/{chunk-WJ5KWJLK.js → chunk-NNEWBRUL.js} +2 -2
- package/dist/{chunk-5IKW2VP6.js → chunk-NPX6WMFJ.js} +2 -2
- package/dist/{chunk-Z22M4JCY.js → chunk-NZLFVLLJ.js} +165 -5
- package/dist/chunk-NZLFVLLJ.js.map +1 -0
- package/dist/{chunk-QKCXRS5A.js → chunk-OGXXGHW6.js} +11 -1
- package/dist/{chunk-QKCXRS5A.js.map → chunk-OGXXGHW6.js.map} +1 -1
- package/dist/{chunk-CO7KBRPF.js → chunk-TJNDFNCU.js} +2 -2
- package/dist/{chunk-OKOG5MXF.js → chunk-XZRZJHBW.js} +10 -10
- package/dist/{chunk-HUQMVI3A.js → chunk-ZBYVR5W4.js} +2 -2
- package/dist/{chunk-ZANEMAEV.js → chunk-ZP73EM2X.js} +2 -2
- package/dist/{chunk-IEOBAOA6.js → chunk-ZXQPAYCS.js} +2 -2
- package/dist/{cli-VGDSn2zY.d.ts → cli-CCc34xV7.d.ts} +1 -1
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +19 -19
- package/dist/compounding/engine.js +3 -3
- package/dist/config.js +2 -2
- package/dist/deep-recall-http-glue.d.ts +1 -1
- package/dist/deep-recall-mcp-tools.d.ts +1 -1
- package/dist/external-wiki-access.d.ts +1 -1
- package/dist/external-wiki-access.js +3 -3
- package/dist/external-wiki-mcp-tools.d.ts +1 -1
- package/dist/index.d.ts +680 -680
- package/dist/index.js +24 -24
- package/dist/mcp-memory-inspector-app.d.ts +1 -1
- package/dist/memory-browse-http-glue.d.ts +1 -1
- package/dist/memory-browse-mcp-tools.d.ts +1 -1
- package/dist/memory-browse-operations.js +3 -3
- package/dist/memory-subject-cli.d.ts +1 -1
- package/dist/memory-subject.d.ts +1 -1
- package/dist/operator-toolkit.js +3 -3
- package/dist/orchestration/maintenance.js +3 -2
- package/dist/orchestrator.js +24 -24
- package/dist/{public-http-P0cnHzYB.d.ts → public-http-UWVcqMcb.d.ts} +1 -1
- package/dist/recall-navigation-http-glue.d.ts +1 -1
- package/dist/recall-navigation-mcp-tools.d.ts +1 -1
- package/dist/recall-navigation-operations.js +3 -3
- package/dist/recall-navigation.js +2 -2
- package/dist/resume-bundles.js +3 -3
- package/dist/schemas.d.ts +160 -160
- package/dist/shared-context/manager.d.ts +24 -8
- package/dist/shared-context/manager.js +2 -2
- package/dist/support-passport/index.d.ts +4 -4
- package/dist/support-passport/index.js +5 -5
- package/dist/transfer/types.d.ts +78 -78
- package/dist/who-knows-cli.d.ts +1 -1
- package/dist/who-knows.d.ts +1 -1
- package/package.json +2 -2
- package/src/activity/config.test.ts +19 -0
- package/src/activity/config.ts +3 -4
- package/src/shared-context/governance-wiring.test.ts +153 -0
- package/src/shared-context/manager.ts +104 -3
- package/src/shared-context/staleness.ts +1 -1
- package/dist/chunk-3KJTSCSX.js.map +0 -1
- package/dist/chunk-Z22M4JCY.js.map +0 -1
- /package/dist/{chunk-ZADYEZY4.js.map → chunk-2SIKTXWX.js.map} +0 -0
- /package/dist/{chunk-ZHV6FGVF.js.map → chunk-3R23DDD3.js.map} +0 -0
- /package/dist/{chunk-EQNZC3BH.js.map → chunk-3S6URXEH.js.map} +0 -0
- /package/dist/{chunk-BCXZ4BDS.js.map → chunk-75YZ5VAI.js.map} +0 -0
- /package/dist/{chunk-MXTCV3B5.js.map → chunk-AHVJ6GLL.js.map} +0 -0
- /package/dist/{chunk-6UEM5EOB.js.map → chunk-AQ55YKEV.js.map} +0 -0
- /package/dist/{chunk-VMKAA5SU.js.map → chunk-BSCNBIF4.js.map} +0 -0
- /package/dist/{chunk-M7HFDWOS.js.map → chunk-FROKVQQY.js.map} +0 -0
- /package/dist/{chunk-A4TQFNRX.js.map → chunk-GRDRVYXJ.js.map} +0 -0
- /package/dist/{chunk-EYK3UHAP.js.map → chunk-H6WOFMOV.js.map} +0 -0
- /package/dist/{chunk-SOOWBRMH.js.map → chunk-IYNCJKBM.js.map} +0 -0
- /package/dist/{chunk-KGY6F4VJ.js.map → chunk-KIGC55FQ.js.map} +0 -0
- /package/dist/{chunk-KQQEZTH6.js.map → chunk-KQVBR7BC.js.map} +0 -0
- /package/dist/{chunk-MTJUIIM4.js.map → chunk-MTWD4KMM.js.map} +0 -0
- /package/dist/{chunk-WJ5KWJLK.js.map → chunk-NNEWBRUL.js.map} +0 -0
- /package/dist/{chunk-5IKW2VP6.js.map → chunk-NPX6WMFJ.js.map} +0 -0
- /package/dist/{chunk-CO7KBRPF.js.map → chunk-TJNDFNCU.js.map} +0 -0
- /package/dist/{chunk-OKOG5MXF.js.map → chunk-XZRZJHBW.js.map} +0 -0
- /package/dist/{chunk-HUQMVI3A.js.map → chunk-ZBYVR5W4.js.map} +0 -0
- /package/dist/{chunk-ZANEMAEV.js.map → chunk-ZP73EM2X.js.map} +0 -0
- /package/dist/{chunk-IEOBAOA6.js.map → chunk-ZXQPAYCS.js.map} +0 -0
|
@@ -2,9 +2,11 @@ import {
|
|
|
2
2
|
composeWriteEnvelope,
|
|
3
3
|
envelopeFromScalars,
|
|
4
4
|
envelopeToFrontmatterLines,
|
|
5
|
+
isExpired,
|
|
6
|
+
isStrictIsoInstant,
|
|
5
7
|
resolveReadAuthority,
|
|
6
8
|
resolveWriteOrigin
|
|
7
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-OGXXGHW6.js";
|
|
8
10
|
import {
|
|
9
11
|
resolveConversationContextCapabilities
|
|
10
12
|
} from "./chunk-JUOZ62Y7.js";
|
|
@@ -23,6 +25,97 @@ import { randomUUID } from "crypto";
|
|
|
23
25
|
import { mkdir, readFile, readdir, appendFile, writeFile, stat, rename, rm } from "fs/promises";
|
|
24
26
|
import path from "path";
|
|
25
27
|
import { z } from "zod";
|
|
28
|
+
|
|
29
|
+
// src/shared-context/contradictions.ts
|
|
30
|
+
function detectContradictionPair(a, b) {
|
|
31
|
+
if (a.id === b.id) {
|
|
32
|
+
return { kind: "same" };
|
|
33
|
+
}
|
|
34
|
+
const keys = [];
|
|
35
|
+
for (const key of Object.keys(a.claims)) {
|
|
36
|
+
if (key in b.claims && a.claims[key] !== b.claims[key]) {
|
|
37
|
+
keys.push(key);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return keys.length > 0 ? { kind: "conflict", keys: keys.sort() } : { kind: "none" };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// src/shared-context/curation-lint.ts
|
|
44
|
+
function lintCuratedClaims(input) {
|
|
45
|
+
const available = new Set(input.availableItemIds);
|
|
46
|
+
const findings = [];
|
|
47
|
+
for (const claim of input.claims) {
|
|
48
|
+
const claimId = claim.claimId;
|
|
49
|
+
if (typeof claimId !== "string" || claimId.trim().length === 0) {
|
|
50
|
+
throw new RangeError("claimId must be a non-blank string");
|
|
51
|
+
}
|
|
52
|
+
const unknown = /* @__PURE__ */ new Set();
|
|
53
|
+
let validCount = 0;
|
|
54
|
+
for (const id of claim.citedItemIds ?? []) {
|
|
55
|
+
if (id.trim().length === 0) continue;
|
|
56
|
+
if (available.has(id)) {
|
|
57
|
+
validCount += 1;
|
|
58
|
+
} else {
|
|
59
|
+
unknown.add(id);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (validCount === 0) {
|
|
63
|
+
findings.push({ claimId, reason: "no_citations" });
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (unknown.size > 0) {
|
|
67
|
+
findings.push({ claimId, reason: "unknown_citation", unknownIds: [...unknown].sort() });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
findings.sort((a, b) => {
|
|
71
|
+
if (a.claimId !== b.claimId) return a.claimId < b.claimId ? -1 : 1;
|
|
72
|
+
if (a.reason !== b.reason) return a.reason < b.reason ? -1 : 1;
|
|
73
|
+
const left = (a.unknownIds ?? []).join(",");
|
|
74
|
+
const right = (b.unknownIds ?? []).join(",");
|
|
75
|
+
if (left !== right) return left < right ? -1 : 1;
|
|
76
|
+
return 0;
|
|
77
|
+
});
|
|
78
|
+
return findings;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/shared-context/provenance.ts
|
|
82
|
+
function requireActor(actor) {
|
|
83
|
+
if (typeof actor !== "string" || actor.trim().length === 0) {
|
|
84
|
+
throw new Error("stampProvenance: actor must be a non-empty string");
|
|
85
|
+
}
|
|
86
|
+
return actor;
|
|
87
|
+
}
|
|
88
|
+
function requireAt(at) {
|
|
89
|
+
if (typeof at !== "string" || !isStrictIsoInstant(at)) {
|
|
90
|
+
throw new Error("stampProvenance: at must be a valid ISO-8601 timestamp");
|
|
91
|
+
}
|
|
92
|
+
return at;
|
|
93
|
+
}
|
|
94
|
+
function stampProvenance(item, stamp) {
|
|
95
|
+
return {
|
|
96
|
+
...item,
|
|
97
|
+
provenance: {
|
|
98
|
+
actor: requireActor(stamp.actor),
|
|
99
|
+
at: requireAt(stamp.at)
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/shared-context/staleness.ts
|
|
105
|
+
function filterLiveEnvelopes(items, nowMs) {
|
|
106
|
+
return items.filter((item) => !isExpired(item, nowMs));
|
|
107
|
+
}
|
|
108
|
+
function markSupersededCirculation(items) {
|
|
109
|
+
const supersededIds = /* @__PURE__ */ new Set();
|
|
110
|
+
for (const item of items) {
|
|
111
|
+
if (item.supersedes) supersededIds.add(item.supersedes);
|
|
112
|
+
}
|
|
113
|
+
return items.map(
|
|
114
|
+
(item) => supersededIds.has(item.id) ? { ...item, circulating: true } : item
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/shared-context/manager.ts
|
|
26
119
|
var SharedFeedbackEntrySchema = z.object({
|
|
27
120
|
agent: z.string().min(1),
|
|
28
121
|
decision: z.enum(["approved", "approved_with_feedback", "rejected"]),
|
|
@@ -317,6 +410,19 @@ function formatFeedbackLine(entry) {
|
|
|
317
410
|
function formatOverlapLine(entry) {
|
|
318
411
|
return `- \`${entry.token}\` (${entry.agentCount} agents: ${markdownLineList(entry.agents)}) [sources: ${markdownLineList(entry.sourcePaths)}]`;
|
|
319
412
|
}
|
|
413
|
+
function formatStalenessLines(report) {
|
|
414
|
+
const circulating = report.staleness.supersededStillCirculating;
|
|
415
|
+
return [
|
|
416
|
+
`- Expired items dropped: ${report.staleness.expiredDropped}`,
|
|
417
|
+
circulating.length === 0 ? "- Superseded items still circulating: 0" : `- Superseded items still circulating: ${circulating.length} (${markdownLineList(circulating)})`
|
|
418
|
+
];
|
|
419
|
+
}
|
|
420
|
+
function formatDisputedLines(report) {
|
|
421
|
+
if (report.disputed.length === 0) return ["- No contradictory agent judgments recorded."];
|
|
422
|
+
return report.disputed.map(
|
|
423
|
+
(entry) => `- \`${entry.ref}\` disputed by ${markdownLineList(entry.agents)} (decisions: ${markdownLineList(entry.decisions)})`
|
|
424
|
+
);
|
|
425
|
+
}
|
|
320
426
|
async function writeFileAtomic(filePath, content) {
|
|
321
427
|
await mkdir(path.dirname(filePath), { recursive: true });
|
|
322
428
|
const tempPath = path.join(
|
|
@@ -561,6 +667,14 @@ var SharedContextManager = class {
|
|
|
561
667
|
outputs.sort(
|
|
562
668
|
(a, b) => a.agent.localeCompare(b.agent) || a.path.localeCompare(b.path) || a.title.localeCompare(b.title)
|
|
563
669
|
);
|
|
670
|
+
const liveOutputs = filterLiveEnvelopes(
|
|
671
|
+
outputs.map((output) => ({ output, expiresAt: output.envelope.expiresAt })),
|
|
672
|
+
Date.now()
|
|
673
|
+
).map((entry) => entry.output);
|
|
674
|
+
const expiredDropped = outputs.length - liveOutputs.length;
|
|
675
|
+
const supersededStillCirculating = markSupersededCirculation(
|
|
676
|
+
liveOutputs.map((output) => ({ id: output.path, supersedes: output.envelope.supersedes }))
|
|
677
|
+
).filter((item) => item.circulating === true).map((item) => item.id).sort();
|
|
564
678
|
const feedback = [];
|
|
565
679
|
try {
|
|
566
680
|
const raw = await readFile(this.feedbackInboxPath, "utf-8");
|
|
@@ -576,7 +690,7 @@ var SharedContextManager = class {
|
|
|
576
690
|
}
|
|
577
691
|
} catch {
|
|
578
692
|
}
|
|
579
|
-
const sources =
|
|
693
|
+
const sources = liveOutputs.map((output) => {
|
|
580
694
|
const body = stripYamlFrontmatter(output.raw);
|
|
581
695
|
return {
|
|
582
696
|
agent: output.agent,
|
|
@@ -643,15 +757,38 @@ ${body}`),
|
|
|
643
757
|
for (const entry of feedback) {
|
|
644
758
|
feedbackByDecision[entry.decision] += 1;
|
|
645
759
|
}
|
|
646
|
-
const
|
|
760
|
+
const claimItems = feedback.map((entry, index) => ({
|
|
761
|
+
id: `${entry.agent}#${index}`,
|
|
762
|
+
claims: Object.fromEntries((entry.refs ?? []).map((ref) => [ref, entry.decision]))
|
|
763
|
+
}));
|
|
764
|
+
const disputedByRef = /* @__PURE__ */ new Map();
|
|
765
|
+
for (let i = 0; i < claimItems.length; i++) {
|
|
766
|
+
for (let j = i + 1; j < claimItems.length; j++) {
|
|
767
|
+
const pair = detectContradictionPair(claimItems[i], claimItems[j]);
|
|
768
|
+
if (pair.kind !== "conflict") continue;
|
|
769
|
+
for (const ref of pair.keys) {
|
|
770
|
+
const slot = disputedByRef.get(ref) ?? { agents: /* @__PURE__ */ new Set(), decisions: /* @__PURE__ */ new Set() };
|
|
771
|
+
slot.agents.add(feedback[i].agent);
|
|
772
|
+
slot.agents.add(feedback[j].agent);
|
|
773
|
+
slot.decisions.add(feedback[i].decision);
|
|
774
|
+
slot.decisions.add(feedback[j].decision);
|
|
775
|
+
disputedByRef.set(ref, slot);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
const disputed = [...disputedByRef.entries()].map(([ref, slot]) => ({ ref, agents: [...slot.agents].sort(), decisions: [...slot.decisions].sort() })).sort((a, b) => a.ref.localeCompare(b.ref));
|
|
780
|
+
const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
781
|
+
const baseReport = {
|
|
647
782
|
date,
|
|
648
|
-
generatedAt
|
|
783
|
+
generatedAt,
|
|
649
784
|
sourceCount: sources.length,
|
|
650
785
|
feedbackCount: feedback.length,
|
|
651
786
|
feedbackByDecision,
|
|
652
787
|
feedbackEntries: [...feedback].sort(compareFeedbackPriority),
|
|
653
788
|
sources,
|
|
654
789
|
overlaps: mergedOverlaps,
|
|
790
|
+
staleness: { expiredDropped, supersededStillCirculating },
|
|
791
|
+
disputed,
|
|
655
792
|
semantic: {
|
|
656
793
|
enabled: semanticEnabled,
|
|
657
794
|
applied: semanticApplied,
|
|
@@ -661,6 +798,7 @@ ${body}`),
|
|
|
661
798
|
addedOverlapCount: semanticAddedOverlapCount
|
|
662
799
|
}
|
|
663
800
|
};
|
|
801
|
+
const report = stampProvenance(baseReport, { actor: "shared-context:curation", at: generatedAt });
|
|
664
802
|
const crossSignalsPath = path.join(this.crossSignalsDir, `${date}.json`);
|
|
665
803
|
await writeFileAtomic(crossSignalsPath, `${JSON.stringify(report, null, 2)}
|
|
666
804
|
`);
|
|
@@ -681,6 +819,12 @@ ${body}`),
|
|
|
681
819
|
`- Semantic enhancer: ${semanticEnabled ? semanticTimedOut ? "enabled (timed out, fail-open)" : semanticApplied ? "enabled (applied)" : "enabled (no additional overlaps)" : "disabled"}`,
|
|
682
820
|
`- JSON report: ${crossSignalsPath}`,
|
|
683
821
|
"",
|
|
822
|
+
"## Staleness",
|
|
823
|
+
...formatStalenessLines(report),
|
|
824
|
+
"",
|
|
825
|
+
"## Disputed",
|
|
826
|
+
...formatDisputedLines(report),
|
|
827
|
+
"",
|
|
684
828
|
"## Recurring Themes",
|
|
685
829
|
...recurringThemeLines,
|
|
686
830
|
"",
|
|
@@ -714,6 +858,16 @@ ${body}`),
|
|
|
714
858
|
const date = opts.date;
|
|
715
859
|
const maxChars = Math.max(2e3, opts.maxChars ?? 2e4);
|
|
716
860
|
const crossSignals = await this.synthesizeCrossSignalsUnlocked({ date });
|
|
861
|
+
const lintFindings = lintCuratedClaims({
|
|
862
|
+
claims: crossSignals.report.overlaps.map((overlap) => ({
|
|
863
|
+
claimId: `overlap:${overlap.token}`,
|
|
864
|
+
citedItemIds: overlap.sourcePaths
|
|
865
|
+
})),
|
|
866
|
+
availableItemIds: crossSignals.report.sources.map((source) => source.path)
|
|
867
|
+
});
|
|
868
|
+
if (lintFindings.length > 0) {
|
|
869
|
+
throw new Error(`shared-context curation self-check failed: ${JSON.stringify(lintFindings)}`);
|
|
870
|
+
}
|
|
717
871
|
const feedbackLines = crossSignals.report.feedbackEntries.length === 0 ? ["- (none)"] : crossSignals.report.feedbackEntries.map((entry) => formatFeedbackLine(entry));
|
|
718
872
|
const overlapBullets = crossSignals.report.overlaps.length === 0 ? ["- No multi-agent topic overlap detected."] : crossSignals.report.overlaps.slice(0, 8).map((entry) => formatOverlapLine(entry));
|
|
719
873
|
const md = [
|
|
@@ -733,6 +887,12 @@ ${body}`),
|
|
|
733
887
|
`- Cross-signals JSON: ${crossSignals.crossSignalsPath}`,
|
|
734
888
|
`- Cross-signals markdown: ${crossSignals.crossSignalsMarkdownPath}`,
|
|
735
889
|
...overlapBullets,
|
|
890
|
+
"",
|
|
891
|
+
"## Staleness",
|
|
892
|
+
...formatStalenessLines(crossSignals.report),
|
|
893
|
+
"",
|
|
894
|
+
"## Disputed",
|
|
895
|
+
...formatDisputedLines(crossSignals.report),
|
|
736
896
|
""
|
|
737
897
|
];
|
|
738
898
|
const out = md.join("\n");
|
|
@@ -755,4 +915,4 @@ export {
|
|
|
755
915
|
resolveSharedContextDir,
|
|
756
916
|
SharedContextManager
|
|
757
917
|
};
|
|
758
|
-
//# sourceMappingURL=chunk-
|
|
918
|
+
//# sourceMappingURL=chunk-NZLFVLLJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/shared-context/manager.ts","../src/shared-context/contradictions.ts","../src/shared-context/curation-lint.ts","../src/shared-context/provenance.ts","../src/shared-context/staleness.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, readdir, appendFile, writeFile, stat, rename, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { z } from \"zod\";\nimport { log } from \"../logger.js\";\nimport type { PluginConfig } from \"../types.js\";\nimport { expandTildePath } from \"../utils/path.js\";\nimport { resolveConversationContextCapabilities } from \"../capabilities.js\";\nimport { throwIfAborted } from \"../abort-error.js\";\nimport {\n composeWriteEnvelope,\n envelopeFromScalars,\n envelopeToFrontmatterLines,\n resolveReadAuthority,\n resolveWriteOrigin,\n} from \"./envelope-io.js\";\nimport type { SharedAuthority, SharedEnvelope } from \"./governance.js\";\nimport { detectContradictionPair } from \"./contradictions.js\";\nimport { lintCuratedClaims } from \"./curation-lint.js\";\nimport { stampProvenance } from \"./provenance.js\";\nimport { filterLiveEnvelopes, markSupersededCirculation } from \"./staleness.js\";\n\nexport const SharedFeedbackEntrySchema = z.object({\n agent: z.string().min(1),\n decision: z.enum([\"approved\", \"approved_with_feedback\", \"rejected\"]),\n reason: z.string().min(1),\n date: z.string().min(8), // ISO-ish; keep loose\n learning: z.string().optional(),\n outcome: z.string().optional(),\n severity: z.enum([\"low\", \"medium\", \"high\"]).optional(),\n confidence: z.number().min(0).max(1).optional(),\n workflow: z.string().min(1).optional(),\n tags: z.array(z.string().min(1)).optional(),\n evidenceWindowStart: z.string().min(8).optional(),\n evidenceWindowEnd: z.string().min(8).optional(),\n refs: z.array(z.string()).optional(),\n});\n\nexport type SharedFeedbackEntry = z.infer<typeof SharedFeedbackEntrySchema>;\n\nfunction safeSlug(s: string): string {\n let slug = s.toLowerCase().replace(/[^a-z0-9]+/g, \"-\");\n // Trim leading/trailing dashes without ReDoS-prone anchored quantifiers\n let start = 0;\n while (start < slug.length && slug[start] === \"-\") start++;\n let end = slug.length;\n while (end > start && slug[end - 1] === \"-\") end--;\n return slug.slice(start, end).slice(0, 80) || \"output\";\n}\n\nfunction safePathSegment(s: string, label: string): string {\n if (s.length === 0) throw new Error(`${label} must not be empty`);\n if (/[\\r\\n]/.test(s)) throw new Error(`${label} must not contain line breaks`);\n const encoded = encodeURIComponent(s);\n if (encoded === \".\" || encoded === \"..\") {\n return encoded.replace(/\\./g, \"%2E\");\n }\n return encoded;\n}\n\nfunction safeDecodePathSegment(s: string): string {\n try {\n return decodeURIComponent(s);\n } catch {\n return s;\n }\n}\n\nfunction normalizeFrontmatterScalar(value: string): string {\n if (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n try {\n const parsed = JSON.parse(value);\n if (typeof parsed === \"string\") return parsed;\n } catch {\n // Fall through to the legacy partial unescape below.\n }\n return value.slice(1, -1).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n }\n if (value.length >= 2 && value.startsWith(\"'\") && value.endsWith(\"'\")) {\n return value.slice(1, -1).replace(/''/g, \"'\");\n }\n return value;\n}\n\nfunction formatFrontmatterScalar(value: string): string {\n return JSON.stringify(value);\n}\n\nfunction readFrontmatterScalar(raw: string, key: string): string | null {\n const frontmatter = raw.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/)?.[1];\n if (!frontmatter) return null;\n for (const line of frontmatter.split(/\\r?\\n/)) {\n if (!line.startsWith(`${key}:`)) continue;\n const value = line.slice(key.length + 1).trim();\n return value ? normalizeFrontmatterScalar(value) : null;\n }\n return null;\n}\n\nfunction ymd(d: Date): string {\n return d.toISOString().slice(0, 10);\n}\n\nfunction safeDateSegment(date: string): string {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(date)) {\n throw new Error(`Invalid shared-context date: ${JSON.stringify(date)}; expected YYYY-MM-DD`);\n }\n const parsed = new Date(`${date}T00:00:00.000Z`);\n if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== date) {\n throw new Error(`Invalid shared-context date: ${JSON.stringify(date)}; expected a real calendar date`);\n }\n return date;\n}\n\nconst CROSS_SIGNAL_STOPWORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"by\",\n \"for\",\n \"from\",\n \"has\",\n \"have\",\n \"in\",\n \"is\",\n \"it\",\n \"of\",\n \"on\",\n \"or\",\n \"that\",\n \"the\",\n \"this\",\n \"to\",\n \"was\",\n \"were\",\n \"with\",\n \"agent\",\n \"output\",\n \"today\",\n \"daily\",\n \"notes\",\n \"note\",\n \"summary\",\n]);\n\nfunction extractTopicTokens(text: string, maxTokens: number = 12): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n const tokens = text\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .split(/\\s+/)\n .map((token) => token.trim())\n .filter((token) => token.length >= 4)\n .filter((token) => !CROSS_SIGNAL_STOPWORDS.has(token));\n\n for (const token of tokens) {\n if (seen.has(token)) continue;\n seen.add(token);\n out.push(token);\n if (out.length >= maxTokens) break;\n }\n return out;\n}\n\nfunction stripYamlFrontmatter(text: string): string {\n if (!text.startsWith(\"---\\n\")) return text;\n const closing = text.indexOf(\"\\n---\\n\", 4);\n if (closing === -1) return text;\n return text.slice(closing + 5);\n}\n\nfunction semanticRoot(token: string): string {\n let root = token.toLowerCase();\n if (root.endsWith(\"izations\") && root.length > 9) {\n root = `${root.slice(0, -8)}ize`;\n }\n else if (root.endsWith(\"ization\") && root.length > 8) {\n root = `${root.slice(0, -7)}ize`;\n } else if (root.endsWith(\"isations\") && root.length > 9) {\n root = `${root.slice(0, -8)}ise`;\n } else if (root.endsWith(\"isation\") && root.length > 8) {\n root = `${root.slice(0, -7)}ise`;\n } else {\n const suffixes = [\n \"ations\",\n \"ation\",\n \"ments\",\n \"ment\",\n \"ingly\",\n \"edly\",\n \"ings\",\n \"ing\",\n \"ers\",\n \"er\",\n \"ies\",\n \"ied\",\n \"ions\",\n \"ion\",\n \"es\",\n \"ed\",\n \"s\",\n ];\n for (const suffix of suffixes) {\n if (root.length > suffix.length + 3 && root.endsWith(suffix)) {\n root = root.slice(0, -suffix.length);\n break;\n }\n }\n }\n if (root.length > 4 && root.endsWith(\"e\")) {\n root = root.slice(0, -1);\n }\n return root;\n}\n\nfunction mergeOverlaps(\n base: SharedCrossSignalOverlap[],\n extra: SharedCrossSignalOverlap[],\n): SharedCrossSignalOverlap[] {\n const merged = new Map<string, { agents: Set<string>; sourcePaths: Set<string> }>();\n for (const entry of [...base, ...extra]) {\n const existing = merged.get(entry.token);\n if (existing) {\n for (const agent of entry.agents) existing.agents.add(agent);\n for (const sourcePath of entry.sourcePaths) existing.sourcePaths.add(sourcePath);\n } else {\n merged.set(entry.token, {\n agents: new Set(entry.agents),\n sourcePaths: new Set(entry.sourcePaths),\n });\n }\n }\n return [...merged.entries()]\n .map(([token, value]) => ({\n token,\n agents: [...value.agents].sort(),\n sourcePaths: [...value.sourcePaths].sort(),\n agentCount: value.agents.size,\n }))\n .filter((entry) => entry.agentCount >= 2)\n .sort((a, b) => b.agentCount - a.agentCount || a.token.localeCompare(b.token));\n}\n\nasync function computeSemanticOverlapCandidates(\n sources: SharedCrossSignalSource[],\n maxCandidates: number,\n timeoutAtMs: number,\n): Promise<{ overlaps: SharedCrossSignalOverlap[]; candidateCount: number; timedOut: boolean }> {\n const tokenRows: Array<{ token: string; agent: string; path: string }> = [];\n for (const source of sources) {\n for (const token of source.topics) {\n if (Date.now() >= timeoutAtMs) return { overlaps: [], candidateCount: tokenRows.length, timedOut: true };\n await new Promise<void>((resolve) => setImmediate(resolve));\n tokenRows.push({ token, agent: source.agent, path: source.path });\n if (tokenRows.length >= maxCandidates) break;\n }\n if (tokenRows.length >= maxCandidates) break;\n }\n\n const byRoot = new Map<string, Map<string, { agents: Set<string>; paths: Set<string> }>>();\n for (const row of tokenRows) {\n if (Date.now() >= timeoutAtMs) return { overlaps: [], candidateCount: tokenRows.length, timedOut: true };\n await new Promise<void>((resolve) => setImmediate(resolve));\n const root = semanticRoot(row.token);\n if (root.length < 4) continue;\n const rootGroup = byRoot.get(root) ?? new Map<string, { agents: Set<string>; paths: Set<string> }>();\n const tokenGroup = rootGroup.get(row.token) ?? { agents: new Set<string>(), paths: new Set<string>() };\n tokenGroup.agents.add(row.agent);\n tokenGroup.paths.add(row.path);\n rootGroup.set(row.token, tokenGroup);\n byRoot.set(root, rootGroup);\n }\n\n const overlaps: SharedCrossSignalOverlap[] = [];\n for (const [root, tokenMap] of byRoot.entries()) {\n if (Date.now() >= timeoutAtMs) return { overlaps: [], candidateCount: tokenRows.length, timedOut: true };\n await new Promise<void>((resolve) => setImmediate(resolve));\n if (tokenMap.size < 2) continue;\n const agents = new Set<string>();\n const sourcePaths = new Set<string>();\n for (const value of tokenMap.values()) {\n for (const agent of value.agents) agents.add(agent);\n for (const sourcePath of value.paths) sourcePaths.add(sourcePath);\n }\n if (agents.size < 2) continue;\n overlaps.push({\n token: `semantic:${root}`,\n agents: [...agents].sort(),\n sourcePaths: [...sourcePaths].sort(),\n agentCount: agents.size,\n });\n }\n\n overlaps.sort((a, b) => b.agentCount - a.agentCount || a.token.localeCompare(b.token));\n return {\n overlaps,\n candidateCount: tokenRows.length,\n timedOut: false,\n };\n}\n\nasync function computeSemanticOverlapsWithTimeout(\n sources: SharedCrossSignalSource[],\n timeoutMs: number,\n maxCandidates: number,\n): Promise<{ overlaps: SharedCrossSignalOverlap[]; candidateCount: number; timedOut: boolean }> {\n const safeTimeoutMs = Math.max(1, Math.floor(timeoutMs));\n const safeMaxCandidates = Math.max(0, Math.floor(maxCandidates));\n if (safeMaxCandidates === 0 || sources.length === 0) {\n return { overlaps: [], candidateCount: 0, timedOut: false };\n }\n const timeoutAtMs = Date.now() + safeTimeoutMs;\n return computeSemanticOverlapCandidates(sources, safeMaxCandidates, timeoutAtMs);\n}\n\ninterface SharedCrossSignalSource {\n agent: string;\n path: string;\n title: string;\n topics: string[];\n /** Resolved least-privilege authority from the item's envelope (issue #1957). */\n authority: SharedAuthority;\n /** Envelope origin agent id; legacy items fall back to the agent field. */\n sharedBy: string;\n}\n\ninterface SharedCrossSignalOverlap {\n token: string;\n agents: string[];\n sourcePaths: string[];\n agentCount: number;\n}\n\ninterface SharedCrossSignalReport {\n date: string;\n generatedAt: string;\n sourceCount: number;\n feedbackCount: number;\n feedbackByDecision: Record<\"approved\" | \"approved_with_feedback\" | \"rejected\", number>;\n feedbackEntries: SharedFeedbackEntry[];\n sources: SharedCrossSignalSource[];\n overlaps: SharedCrossSignalOverlap[];\n /** Control 2 (issue #1957): expiry drops and supersession circulation. */\n staleness: {\n expiredDropped: number;\n supersededStillCirculating: string[];\n };\n /** Control 3 (issue #1957): refs two agents ruled on differently. */\n disputed: Array<{ ref: string; agents: string[]; decisions: string[] }>;\n /** Control 4 (issue #1957): who synthesized this report and when. */\n provenance: { actor: string; at: string };\n semantic: {\n enabled: boolean;\n applied: boolean;\n timedOut: boolean;\n candidateCount: number;\n maxCandidates: number;\n addedOverlapCount: number;\n };\n}\n\nexport interface SharedCrossSignalSynthesisResult {\n date: string;\n crossSignalsPath: string;\n crossSignalsMarkdownPath: string;\n overlapCount: number;\n report: SharedCrossSignalReport;\n}\n\nexport interface SharedDailyCurationResult {\n date: string;\n roundtablePath: string;\n crossSignalsPath: string;\n crossSignalsMarkdownPath: string;\n overlapCount: number;\n}\n\nfunction feedbackDecisionPriority(decision: SharedFeedbackEntry[\"decision\"]): number {\n switch (decision) {\n case \"rejected\":\n return 3;\n case \"approved_with_feedback\":\n return 2;\n case \"approved\":\n return 1;\n }\n}\n\nfunction feedbackSeverityPriority(severity: SharedFeedbackEntry[\"severity\"]): number {\n switch (severity) {\n case \"high\":\n return 3;\n case \"medium\":\n return 2;\n case \"low\":\n return 1;\n default:\n return 0;\n }\n}\n\nfunction compareFeedbackPriority(a: SharedFeedbackEntry, b: SharedFeedbackEntry): number {\n return (\n feedbackDecisionPriority(b.decision) - feedbackDecisionPriority(a.decision)\n || feedbackSeverityPriority(b.severity) - feedbackSeverityPriority(a.severity)\n || a.date.localeCompare(b.date)\n );\n}\n\nfunction markdownLineText(value: string): string {\n return value.replace(/[\\r\\n]+/g, \" \").replace(/\\s+/g, \" \").trim();\n}\n\nfunction markdownLineList(values: readonly string[]): string {\n return values.map(markdownLineText).filter(Boolean).join(\", \");\n}\n\nfunction formatFeedbackLine(entry: SharedFeedbackEntry): string {\n const extras: string[] = [`feedback: ${markdownLineText(entry.date)}`];\n if (entry.severity) extras.push(`severity: ${markdownLineText(entry.severity)}`);\n if (entry.refs?.length) extras.push(`refs: ${markdownLineList(entry.refs)}`);\n return `- [${markdownLineText(entry.agent)}] ${entry.decision}: ${markdownLineText(entry.reason)} [${extras.join(\"; \")}]`;\n}\n\nfunction formatOverlapLine(entry: SharedCrossSignalOverlap): string {\n return `- \\`${entry.token}\\` (${entry.agentCount} agents: ${markdownLineList(entry.agents)}) [sources: ${markdownLineList(entry.sourcePaths)}]`;\n}\n\nfunction formatStalenessLines(report: SharedCrossSignalReport): string[] {\n const circulating = report.staleness.supersededStillCirculating;\n return [\n `- Expired items dropped: ${report.staleness.expiredDropped}`,\n circulating.length === 0\n ? \"- Superseded items still circulating: 0\"\n : `- Superseded items still circulating: ${circulating.length} (${markdownLineList(circulating)})`,\n ];\n}\n\nfunction formatDisputedLines(report: SharedCrossSignalReport): string[] {\n if (report.disputed.length === 0) return [\"- No contradictory agent judgments recorded.\"];\n return report.disputed.map((entry) =>\n `- \\`${entry.ref}\\` disputed by ${markdownLineList(entry.agents)} (decisions: ${markdownLineList(entry.decisions)})`\n );\n}\n\nasync function writeFileAtomic(filePath: string, content: string): Promise<void> {\n await mkdir(path.dirname(filePath), { recursive: true });\n const tempPath = path.join(\n path.dirname(filePath),\n `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,\n );\n try {\n await writeFile(tempPath, content, { encoding: \"utf-8\", flag: \"wx\" });\n await rename(tempPath, filePath);\n } catch (error) {\n await rm(tempPath, { force: true }).catch(() => undefined);\n throw error;\n }\n}\n\nexport function resolveSharedContextDir(config: PluginConfig): string {\n return typeof config.sharedContextDir === \"string\" && config.sharedContextDir.length > 0\n ? expandTildePath(config.sharedContextDir)\n : path.join(expandTildePath(config.workspaceDir), \"shared-context\");\n}\n\nexport class SharedContextManager {\n readonly dir: string;\n private readonly prioritiesPath: string;\n private readonly prioritiesInboxPath: string;\n private readonly outputsDir: string;\n private readonly roundtableDir: string;\n private readonly feedbackDir: string;\n private readonly feedbackInboxPath: string;\n private readonly crossSignalsDir: string;\n private readonly allowBindingAuthority: boolean;\n private readonly dailySynthesisChains = new Map<string, Promise<void>>();\n\n constructor(private readonly config: PluginConfig) {\n const base = resolveSharedContextDir(config);\n\n this.dir = base;\n this.prioritiesPath = path.join(base, \"priorities.md\");\n this.prioritiesInboxPath = path.join(base, \"priorities.inbox.md\");\n this.outputsDir = path.join(base, \"agent-outputs\");\n this.roundtableDir = path.join(base, \"roundtable\");\n this.feedbackDir = path.join(base, \"feedback\");\n this.feedbackInboxPath = path.join(this.feedbackDir, \"inbox.jsonl\");\n this.crossSignalsDir = path.join(base, \"cross-signals\");\n this.allowBindingAuthority = config.sharedContextAllowBindingAuthority === true;\n }\n\n async ensureStructure(): Promise<void> {\n await mkdir(this.dir, { recursive: true });\n await mkdir(this.outputsDir, { recursive: true });\n await mkdir(this.roundtableDir, { recursive: true });\n await mkdir(this.feedbackDir, { recursive: true });\n await mkdir(this.crossSignalsDir, { recursive: true });\n await mkdir(path.join(this.dir, \"staging\"), { recursive: true });\n await mkdir(path.join(this.dir, \"kpis\"), { recursive: true });\n await mkdir(path.join(this.dir, \"calendar\"), { recursive: true });\n await mkdir(path.join(this.dir, \"content-calendar\"), { recursive: true });\n\n // Bootstrap files if missing.\n await this.ensureFile(\n this.prioritiesPath,\n [\n \"# Priorities\",\n \"\",\n \"This is the shared priority stack. Agents should read this before acting.\",\n \"\",\n \"## Current\",\n \"- (empty)\",\n \"\",\n \"## Notes\",\n \"- (empty)\",\n \"\",\n ].join(\"\\n\"),\n );\n await this.ensureFile(\n this.prioritiesInboxPath,\n [\n \"# Priorities Inbox\",\n \"\",\n \"Append-only inbox. Curator merges into priorities.md.\",\n \"\",\n ].join(\"\\n\"),\n );\n await this.ensureFile(this.feedbackInboxPath, \"\");\n }\n\n private async ensureFile(fp: string, content: string): Promise<void> {\n try {\n await stat(fp);\n } catch {\n await writeFile(fp, content, \"utf-8\");\n }\n }\n\n async readPriorities(signal?: AbortSignal): Promise<string> {\n throwIfAborted(signal, \"shared context priorities read aborted\");\n try {\n const content = await readFile(this.prioritiesPath, { encoding: \"utf-8\", signal });\n throwIfAborted(signal, \"shared context priorities read aborted\");\n return content;\n } catch {\n throwIfAborted(signal, \"shared context priorities read aborted\");\n return \"\";\n }\n }\n\n async readLatestRoundtable(signal?: AbortSignal): Promise<string> {\n throwIfAborted(signal, \"shared context roundtable read aborted\");\n try {\n const files = (await readdir(this.roundtableDir))\n .filter((f) => f.endsWith(\".md\"))\n .sort()\n .reverse();\n throwIfAborted(signal, \"shared context roundtable read aborted\");\n const fp = files[0] ? path.join(this.roundtableDir, files[0]) : null;\n if (!fp) return \"\";\n const content = await readFile(fp, { encoding: \"utf-8\", signal });\n throwIfAborted(signal, \"shared context roundtable read aborted\");\n return content;\n } catch {\n throwIfAborted(signal, \"shared context roundtable read aborted\");\n return \"\";\n }\n }\n\n async readLatestCrossSignals(signal?: AbortSignal): Promise<string> {\n throwIfAborted(signal, \"shared context cross-signals read aborted\");\n try {\n const files = (await readdir(this.crossSignalsDir))\n .filter((f) => f.endsWith(\".md\"))\n .sort()\n .reverse();\n throwIfAborted(signal, \"shared context cross-signals read aborted\");\n const fp = files[0] ? path.join(this.crossSignalsDir, files[0]) : null;\n if (!fp) return \"\";\n const content = await readFile(fp, { encoding: \"utf-8\", signal });\n throwIfAborted(signal, \"shared context cross-signals read aborted\");\n return content;\n } catch {\n throwIfAborted(signal, \"shared context cross-signals read aborted\");\n return \"\";\n }\n }\n\n async writeAgentOutput(opts: {\n agentId: string;\n title: string;\n content: string;\n createdAt?: Date;\n /** Envelope authority class (issue #1957). Unrecognized values throw. */\n authority?: string;\n /** Optional ISO-8601 expiry stamped on the item. */\n expiresAt?: string;\n /** Optional id of the shared item this output supersedes. */\n supersedes?: string;\n /**\n * Server-resolved identity of the caller, supplied by the access\n * surface (issue #1957 review). When present it IS both the producer\n * and the envelope origin; a disagreeing caller-supplied `agentId` is\n * rejected so no caller can publish as another agent.\n */\n authenticatedIdentity?: string;\n /**\n * Server-owned origin token for a write that crosses an external\n * boundary but resolved no identity (issue #1957 review round 4).\n * Stamped as the envelope origin (`sharedBy`); the caller label stays\n * the producer so grouping never collapses.\n */\n unattributedOrigin?: string;\n }): Promise<string> {\n const identity = resolveWriteOrigin({\n agentId: opts.agentId,\n authenticatedIdentity: opts.authenticatedIdentity,\n unattributedOrigin: opts.unattributedOrigin,\n });\n const createdAt = opts.createdAt ?? new Date();\n const date = ymd(createdAt);\n const time = createdAt.toISOString().slice(11, 19).replace(/:/g, \"\");\n const slug = safeSlug(opts.title);\n const agentPathSegment = safePathSegment(identity.agent, \"agentId\");\n\n const envelope = composeWriteEnvelope({\n origin: identity.origin,\n authority: opts.authority,\n expiresAt: opts.expiresAt,\n supersedes: opts.supersedes,\n allowBinding: this.allowBindingAuthority,\n nowMs: createdAt.getTime(),\n });\n\n const dir = path.join(this.outputsDir, agentPathSegment, date);\n await mkdir(dir, { recursive: true });\n\n const body = [\n \"---\",\n \"kind: agent_output\",\n `agent: ${formatFrontmatterScalar(identity.agent)}`,\n `createdAt: ${createdAt.toISOString()}`,\n `title: ${formatFrontmatterScalar(opts.title.replace(/\\n/g, \" \").slice(0, 200))}`,\n ...envelopeToFrontmatterLines(envelope),\n \"---\",\n \"\",\n opts.content.trimEnd(),\n \"\",\n ].join(\"\\n\");\n\n for (let attempt = 0; attempt < 100; attempt++) {\n const suffix = attempt === 0 ? \"\" : `-${attempt + 1}`;\n const fp = path.join(dir, `${time}-${slug}${suffix}.md`);\n try {\n await writeFile(fp, body, { encoding: \"utf-8\", flag: \"wx\" });\n return fp;\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"EEXIST\") continue;\n throw error;\n }\n }\n\n throw new Error(`Unable to allocate unique shared-context output path for ${identity.agent}`);\n }\n\n async appendFeedback(entry: SharedFeedbackEntry): Promise<void> {\n const parsed = SharedFeedbackEntrySchema.parse(entry);\n await appendFile(this.feedbackInboxPath, JSON.stringify(parsed) + \"\\n\", \"utf-8\");\n }\n\n async appendPrioritiesInbox(opts: { agentId: string; text: string }): Promise<void> {\n const stamp = new Date().toISOString();\n const lines = [\n \"\",\n `## ${stamp} (${opts.agentId})`,\n \"\",\n opts.text.trimEnd(),\n \"\",\n ].join(\"\\n\");\n await appendFile(this.prioritiesInboxPath, lines, \"utf-8\");\n }\n\n private async withDailySynthesisLock<T>(date: string, fn: () => Promise<T>): Promise<T> {\n const previous = this.dailySynthesisChains.get(date) ?? Promise.resolve();\n let releaseCurrent!: () => void;\n const current = new Promise<void>((resolve) => {\n releaseCurrent = resolve;\n });\n const queued = previous.catch(() => undefined).then(() => current);\n this.dailySynthesisChains.set(date, queued);\n await previous.catch(() => undefined);\n try {\n return await fn();\n } finally {\n releaseCurrent();\n if (this.dailySynthesisChains.get(date) === queued) {\n this.dailySynthesisChains.delete(date);\n }\n }\n }\n\n async synthesizeCrossSignals(opts: {\n date?: string;\n maxSummaryItems?: number;\n }): Promise<SharedCrossSignalSynthesisResult> {\n const date = safeDateSegment(opts.date ?? ymd(new Date()));\n return this.withDailySynthesisLock(date, () => this.synthesizeCrossSignalsUnlocked({\n date,\n maxSummaryItems: opts.maxSummaryItems,\n }));\n }\n\n private async synthesizeCrossSignalsUnlocked(opts: {\n date: string;\n maxSummaryItems?: number;\n }): Promise<SharedCrossSignalSynthesisResult> {\n const date = opts.date;\n const maxSummaryItems = Math.max(1, opts.maxSummaryItems ?? 8);\n\n // Collect outputs for the day (best-effort).\n const outputs: Array<{ agent: string; path: string; title: string; raw: string; envelope: SharedEnvelope }> = [];\n try {\n const agents = (await readdir(this.outputsDir, { withFileTypes: true }))\n .sort((a, b) => a.name.localeCompare(b.name));\n for (const a of agents) {\n if (!a.isDirectory()) continue;\n const dayDir = path.join(this.outputsDir, a.name, date);\n try {\n const files = (await readdir(dayDir)).filter((f) => f.endsWith(\".md\")).sort();\n for (const f of files) {\n const p = path.join(dayDir, f);\n const raw = await readFile(p, \"utf-8\");\n const title = readFrontmatterScalar(raw, \"title\") ?? f;\n const agent = readFrontmatterScalar(raw, \"agent\") ?? safeDecodePathSegment(a.name);\n const envelope = envelopeFromScalars({\n sharedBy: readFrontmatterScalar(raw, \"sharedBy\"),\n authority: readFrontmatterScalar(raw, \"authority\"),\n expiresAt: readFrontmatterScalar(raw, \"expiresAt\"),\n supersedes: readFrontmatterScalar(raw, \"supersedes\"),\n });\n outputs.push({ agent, path: p, title, raw, envelope });\n }\n } catch {\n // no outputs for this agent/date\n }\n }\n } catch {\n // ignore\n }\n outputs.sort(\n (a, b) =>\n a.agent.localeCompare(b.agent)\n || a.path.localeCompare(b.path)\n || a.title.localeCompare(b.title),\n );\n\n // Control 2 (issue #1957): expired items never enter the working set;\n // items another live item supersedes are marked while they circulate.\n const liveOutputs = filterLiveEnvelopes(\n outputs.map((output) => ({ output, expiresAt: output.envelope.expiresAt })),\n Date.now(),\n ).map((entry) => entry.output);\n const expiredDropped = outputs.length - liveOutputs.length;\n const supersededStillCirculating = markSupersededCirculation(\n liveOutputs.map((output) => ({ id: output.path, supersedes: output.envelope.supersedes })),\n )\n .filter((item) => item.circulating === true)\n .map((item) => item.id)\n .sort();\n\n // Collect feedback entries for the day.\n const feedback: SharedFeedbackEntry[] = [];\n try {\n const raw = await readFile(this.feedbackInboxPath, \"utf-8\");\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) continue;\n try {\n const obj = JSON.parse(line);\n const parsed = SharedFeedbackEntrySchema.safeParse(obj);\n if (!parsed.success) continue;\n if (String(parsed.data.date).startsWith(date)) feedback.push(parsed.data);\n } catch {\n // ignore\n }\n }\n } catch {\n // ignore\n }\n\n const sources: SharedCrossSignalSource[] = liveOutputs.map((output) => {\n const body = stripYamlFrontmatter(output.raw);\n return {\n agent: output.agent,\n path: output.path,\n title: output.title,\n topics: extractTopicTokens(`${output.title}\\n${body}`),\n authority: resolveReadAuthority(output.envelope, this.allowBindingAuthority),\n sharedBy: output.envelope.sharedBy ?? output.agent,\n };\n });\n\n const overlapMap = new Map<string, { agents: Set<string>; sourcePaths: Set<string> }>();\n for (const source of sources) {\n for (const token of source.topics) {\n const existing = overlapMap.get(token);\n if (existing) {\n existing.agents.add(source.agent);\n existing.sourcePaths.add(source.path);\n } else {\n overlapMap.set(token, {\n agents: new Set([source.agent]),\n sourcePaths: new Set([source.path]),\n });\n }\n }\n }\n\n const overlaps: SharedCrossSignalOverlap[] = [...overlapMap.entries()]\n .map(([token, v]) => ({\n token,\n agents: [...v.agents].sort(),\n sourcePaths: [...v.sourcePaths].sort(),\n agentCount: v.agents.size,\n }))\n .filter((entry) => entry.agentCount >= 2)\n .sort((a, b) => b.agentCount - a.agentCount || a.token.localeCompare(b.token));\n\n const semanticEnabled =\n resolveConversationContextCapabilities(this.config).sharedCrossSignalSemantic === true\n || resolveConversationContextCapabilities(this.config).crossSignalsSemantic === true;\n const semanticTimeoutMs =\n this.config.sharedCrossSignalSemanticTimeoutMs\n ?? this.config.crossSignalsSemanticTimeoutMs\n ?? 4000;\n const semanticMaxCandidates = this.config.sharedCrossSignalSemanticMaxCandidates ?? 120;\n let semanticApplied = false;\n let semanticTimedOut = false;\n let semanticCandidateCount = 0;\n let semanticAddedOverlapCount = 0;\n let mergedOverlaps = overlaps;\n if (semanticEnabled) {\n try {\n const semanticResult = await computeSemanticOverlapsWithTimeout(\n sources,\n semanticTimeoutMs,\n semanticMaxCandidates,\n );\n semanticTimedOut = semanticResult.timedOut;\n semanticCandidateCount = semanticResult.candidateCount;\n if (!semanticResult.timedOut && semanticResult.overlaps.length > 0) {\n mergedOverlaps = mergeOverlaps(overlaps, semanticResult.overlaps);\n semanticAddedOverlapCount = Math.max(0, mergedOverlaps.length - overlaps.length);\n semanticApplied = semanticAddedOverlapCount > 0;\n }\n } catch (err) {\n log.warn(`shared-context semantic cross-signals failed; fail-open to deterministic output: ${err}`);\n }\n }\n\n const feedbackByDecision: SharedCrossSignalReport[\"feedbackByDecision\"] = {\n approved: 0,\n approved_with_feedback: 0,\n rejected: 0,\n };\n for (const entry of feedback) {\n feedbackByDecision[entry.decision] += 1;\n }\n\n // Control 3 (issue #1957): feedback refs are claim keys; two agents\n // ruling differently on the same ref surface as disputed, never silently\n // averaged. Pairwise scan is bounded by one day's feedback entries.\n const claimItems = feedback.map((entry, index) => ({\n id: `${entry.agent}#${index}`,\n claims: Object.fromEntries((entry.refs ?? []).map((ref) => [ref, entry.decision])),\n }));\n const disputedByRef = new Map<string, { agents: Set<string>; decisions: Set<string> }>();\n for (let i = 0; i < claimItems.length; i++) {\n for (let j = i + 1; j < claimItems.length; j++) {\n const pair = detectContradictionPair(claimItems[i]!, claimItems[j]!);\n if (pair.kind !== \"conflict\") continue;\n for (const ref of pair.keys) {\n const slot = disputedByRef.get(ref) ?? { agents: new Set<string>(), decisions: new Set<string>() };\n slot.agents.add(feedback[i]!.agent);\n slot.agents.add(feedback[j]!.agent);\n slot.decisions.add(feedback[i]!.decision);\n slot.decisions.add(feedback[j]!.decision);\n disputedByRef.set(ref, slot);\n }\n }\n }\n const disputed = [...disputedByRef.entries()]\n .map(([ref, slot]) => ({ ref, agents: [...slot.agents].sort(), decisions: [...slot.decisions].sort() }))\n .sort((a, b) => a.ref.localeCompare(b.ref));\n\n const generatedAt = new Date().toISOString();\n const baseReport = {\n date,\n generatedAt,\n sourceCount: sources.length,\n feedbackCount: feedback.length,\n feedbackByDecision,\n feedbackEntries: [...feedback].sort(compareFeedbackPriority),\n sources,\n overlaps: mergedOverlaps,\n staleness: { expiredDropped, supersededStillCirculating },\n disputed,\n semantic: {\n enabled: semanticEnabled,\n applied: semanticApplied,\n timedOut: semanticTimedOut,\n candidateCount: semanticCandidateCount,\n maxCandidates: Math.max(0, Math.floor(semanticMaxCandidates)),\n addedOverlapCount: semanticAddedOverlapCount,\n },\n };\n // Control 4 (issue #1957): stamp who synthesized the report and when.\n const report = stampProvenance(baseReport, { actor: \"shared-context:curation\", at: generatedAt });\n\n const crossSignalsPath = path.join(this.crossSignalsDir, `${date}.json`);\n await writeFileAtomic(crossSignalsPath, `${JSON.stringify(report, null, 2)}\\n`);\n\n const recurringThemeLines = mergedOverlaps.length === 0\n ? [\"- No multi-agent topic overlap detected.\"]\n : mergedOverlaps.slice(0, maxSummaryItems).map((entry) => formatOverlapLine(entry));\n const riskSignals = [...feedback]\n .filter((entry) => entry.decision !== \"approved\" || entry.severity === \"high\" || entry.severity === \"medium\")\n .sort(compareFeedbackPriority)\n .slice(0, maxSummaryItems);\n const riskLines = riskSignals.length === 0\n ? [\"- No explicit blockers or elevated review risks recorded.\"]\n : riskSignals.map((entry) => formatFeedbackLine(entry));\n const promotionCandidates = mergedOverlaps\n .filter((entry) => entry.agentCount >= 3)\n .slice(0, maxSummaryItems);\n const promotionLines = promotionCandidates.length === 0\n ? [\"- No promotion candidates yet.\"]\n : promotionCandidates.map((entry) =>\n `- Consider promoting \\`${entry.token}\\` into priorities or operating rules [sources: ${markdownLineList(entry.sourcePaths)}]`\n );\n\n const crossSignalsMarkdown = [\n `# Cross-Signals — ${date}`,\n \"\",\n \"## Overview\",\n `- Source outputs analyzed: ${sources.length}`,\n `- Feedback entries analyzed: ${feedback.length}`,\n `- Decision totals: approved=${feedbackByDecision.approved}, approved_with_feedback=${feedbackByDecision.approved_with_feedback}, rejected=${feedbackByDecision.rejected}`,\n `- Semantic enhancer: ${semanticEnabled ? (semanticTimedOut ? \"enabled (timed out, fail-open)\" : semanticApplied ? \"enabled (applied)\" : \"enabled (no additional overlaps)\") : \"disabled\"}`,\n `- JSON report: ${crossSignalsPath}`,\n \"\",\n \"## Staleness\",\n ...formatStalenessLines(report),\n \"\",\n \"## Disputed\",\n ...formatDisputedLines(report),\n \"\",\n \"## Recurring Themes\",\n ...recurringThemeLines,\n \"\",\n \"## Risks And Blockers\",\n ...riskLines,\n \"\",\n \"## Potential Promotions\",\n ...promotionLines,\n \"\",\n \"## Sources\",\n ...(sources.length === 0 ? [\"- (none)\"] : sources.map((source) =>\n `- [${markdownLineText(source.agent)}] ${markdownLineText(source.title)} (${markdownLineText(source.path)}) [authority: ${source.authority}; sharedBy: ${markdownLineText(source.sharedBy)}]`\n )),\n \"\",\n ].join(\"\\n\");\n\n const crossSignalsMarkdownPath = path.join(this.crossSignalsDir, `${date}.md`);\n await writeFileAtomic(crossSignalsMarkdownPath, crossSignalsMarkdown);\n\n return {\n date,\n crossSignalsPath,\n crossSignalsMarkdownPath,\n overlapCount: mergedOverlaps.length,\n report,\n };\n }\n\n async curateDaily(opts: { date?: string; maxChars?: number }): Promise<SharedDailyCurationResult> {\n const date = safeDateSegment(opts.date ?? ymd(new Date()));\n return this.withDailySynthesisLock(date, () => this.curateDailyUnlocked({ ...opts, date }));\n }\n\n private async curateDailyUnlocked(opts: { date: string; maxChars?: number }): Promise<SharedDailyCurationResult> {\n const date = opts.date;\n const maxChars = Math.max(2_000, opts.maxChars ?? 20_000);\n const crossSignals = await this.synthesizeCrossSignalsUnlocked({ date });\n // Control 4 (issue #1957): every synthesized claim must cite at least one\n // item this run actually had. Overlaps are built from sources, so this is\n // a tripwire — it fires only if a synthesized section stops citing.\n const lintFindings = lintCuratedClaims({\n claims: crossSignals.report.overlaps.map((overlap) => ({\n claimId: `overlap:${overlap.token}`,\n citedItemIds: overlap.sourcePaths,\n })),\n availableItemIds: crossSignals.report.sources.map((source) => source.path),\n });\n if (lintFindings.length > 0) {\n throw new Error(`shared-context curation self-check failed: ${JSON.stringify(lintFindings)}`);\n }\n const feedbackLines = crossSignals.report.feedbackEntries.length === 0\n ? [\"- (none)\"]\n : crossSignals.report.feedbackEntries.map((entry) => formatFeedbackLine(entry));\n const overlapBullets = crossSignals.report.overlaps.length === 0\n ? [\"- No multi-agent topic overlap detected.\"]\n : crossSignals.report.overlaps.slice(0, 8).map((entry) => formatOverlapLine(entry));\n\n const md: string[] = [\n `# Roundtable — ${date}`,\n \"\",\n \"## Notable Agent Outputs\",\n ...(crossSignals.report.sources.length === 0\n ? [\"- (none)\"]\n : crossSignals.report.sources.map((source) =>\n `- ${markdownLineText(source.title)} (${markdownLineText(source.path)}) [authority: ${source.authority}; sharedBy: ${markdownLineText(source.sharedBy)}]`)),\n \"\",\n \"## Feedback (Approve/Reject)\",\n ...feedbackLines,\n \"\",\n \"## Cross-Signals\",\n `- Source outputs analyzed: ${crossSignals.report.sourceCount}`,\n `- Feedback entries analyzed: ${crossSignals.report.feedbackCount}`,\n `- Decision totals: approved=${crossSignals.report.feedbackByDecision.approved}, approved_with_feedback=${crossSignals.report.feedbackByDecision.approved_with_feedback}, rejected=${crossSignals.report.feedbackByDecision.rejected}`,\n `- Semantic enhancer: ${crossSignals.report.semantic.enabled ? (crossSignals.report.semantic.timedOut ? \"enabled (timed out, fail-open)\" : crossSignals.report.semantic.applied ? \"enabled (applied)\" : \"enabled (no additional overlaps)\") : \"disabled\"}`,\n `- Cross-signals JSON: ${crossSignals.crossSignalsPath}`,\n `- Cross-signals markdown: ${crossSignals.crossSignalsMarkdownPath}`,\n ...overlapBullets,\n \"\",\n \"## Staleness\",\n ...formatStalenessLines(crossSignals.report),\n \"\",\n \"## Disputed\",\n ...formatDisputedLines(crossSignals.report),\n \"\",\n ];\n\n\n const out = md.join(\"\\n\");\n const trimmed = out.length > maxChars ? out.slice(0, maxChars) + \"\\n\\n...(trimmed)\\n\" : out;\n\n const roundtablePath = path.join(this.roundtableDir, `${date}.md`);\n await writeFileAtomic(roundtablePath, trimmed);\n\n log.info(`shared-context curated daily roundtable: ${roundtablePath}`);\n return {\n date,\n roundtablePath,\n crossSignalsPath: crossSignals.crossSignalsPath,\n crossSignalsMarkdownPath: crossSignals.crossSignalsMarkdownPath,\n overlapCount: crossSignals.overlapCount,\n };\n }\n}\n","/**\n * Shared-item contradiction detection (issue #1957).\n *\n * Pure helper. Same-id items are one item; overlapping claim keys with\n * unequal values are a conflict. No deletes, no persistence.\n */\n\nexport interface SharedClaimItem {\n id: string;\n claims: Record<string, string>;\n}\n\nexport type ContradictionPairResult =\n | { kind: \"same\" }\n | { kind: \"conflict\"; keys: string[] }\n | { kind: \"none\" };\n\nexport function detectContradictionPair(\n a: SharedClaimItem,\n b: SharedClaimItem,\n): ContradictionPairResult {\n if (a.id === b.id) {\n return { kind: \"same\" };\n }\n const keys: string[] = [];\n for (const key of Object.keys(a.claims)) {\n if (key in b.claims && a.claims[key] !== b.claims[key]) {\n keys.push(key);\n }\n }\n return keys.length > 0 ? { kind: \"conflict\", keys: keys.sort() } : { kind: \"none\" };\n}\n","/**\n * Shared-context curation self-check (issue #1957 requirement 4).\n *\n * Pure. A synthesized claim with no traceable source is a lint error:\n * report claims whose citations are missing, blank, or absent from the\n * item ids the curation run actually had available.\n */\n\nexport interface CuratedClaim {\n claimId: string;\n /** Shared-context item ids this claim was synthesized from. */\n citedItemIds?: readonly string[];\n}\n\nexport interface CurationLintFinding {\n claimId: string;\n reason: \"no_citations\" | \"unknown_citation\";\n /** Cited ids that are not in the available set. Only for unknown_citation. */\n unknownIds?: string[];\n}\n\nexport function lintCuratedClaims(input: {\n claims: readonly CuratedClaim[];\n availableItemIds: readonly string[];\n}): CurationLintFinding[] {\n const available = new Set(input.availableItemIds);\n const findings: CurationLintFinding[] = [];\n\n for (const claim of input.claims) {\n const claimId = claim.claimId;\n if (typeof claimId !== \"string\" || claimId.trim().length === 0) {\n throw new RangeError(\"claimId must be a non-blank string\");\n }\n\n const unknown = new Set<string>();\n let validCount = 0;\n for (const id of claim.citedItemIds ?? []) {\n if (id.trim().length === 0) continue;\n if (available.has(id)) {\n validCount += 1;\n } else {\n unknown.add(id);\n }\n }\n\n if (validCount === 0) {\n findings.push({ claimId, reason: \"no_citations\" });\n continue;\n }\n if (unknown.size > 0) {\n findings.push({ claimId, reason: \"unknown_citation\", unknownIds: [...unknown].sort() });\n }\n }\n\n findings.sort((a, b) => {\n if (a.claimId !== b.claimId) return a.claimId < b.claimId ? -1 : 1;\n if (a.reason !== b.reason) return a.reason < b.reason ? -1 : 1;\n // Duplicate claim ids are linted independently, so two findings can share\n // both keys above and still differ. Without this tertiary key the result\n // would depend on upstream iteration order, which the deterministic-output\n // contract forbids.\n const left = (a.unknownIds ?? []).join(\",\");\n const right = (b.unknownIds ?? []).join(\",\");\n if (left !== right) return left < right ? -1 : 1;\n return 0;\n });\n return findings;\n}\n","/**\n * Shared-item provenance stamp (issue #1957).\n *\n * First slice: stamp actor + at onto a new object. Curation wiring\n * comes later. Does not mutate the input.\n */\n\nimport { isStrictIsoInstant } from \"./iso-instant.js\";\n\nexport interface ProvenanceStamp {\n actor: string;\n at: string;\n}\n\nexport interface StampProvenanceOptions {\n actor: string;\n at: string;\n}\n\nfunction requireActor(actor: string): string {\n if (typeof actor !== \"string\" || actor.trim().length === 0) {\n throw new Error(\"stampProvenance: actor must be a non-empty string\");\n }\n return actor;\n}\n\nfunction requireAt(at: unknown): string {\n if (typeof at !== \"string\" || !isStrictIsoInstant(at)) {\n throw new Error(\"stampProvenance: at must be a valid ISO-8601 timestamp\");\n }\n return at;\n}\n\nexport function stampProvenance<T extends object>(\n item: T,\n stamp: StampProvenanceOptions,\n): T & { provenance: ProvenanceStamp } {\n return {\n ...item,\n provenance: {\n actor: requireActor(stamp.actor),\n at: requireAt(stamp.at),\n },\n };\n}\n","/**\n * Shared-item staleness (issue #1957).\n *\n * Pure helpers. Expired items drop; superseded items that still circulate\n * get a marker. Callers never `rm`.\n */\nimport { isExpired } from \"./governance.js\";\n\nexport interface SharedStalenessItem {\n id: string;\n expiresAt?: string;\n supersedes?: string;\n circulating?: boolean;\n}\n\n/** Drop expired items. Half-open: `nowMs >= expiresAt` is expired. */\nexport function filterLiveEnvelopes<T extends { expiresAt?: string }>(\n items: readonly T[],\n nowMs: number,\n): T[] {\n return items.filter((item) => !isExpired(item, nowMs));\n}\n\n/**\n * Mark items whose id appears in another item's `supersedes`.\n * Returns a new array. Does not mutate input and does not delete files.\n */\nexport function markSupersededCirculation<T extends SharedStalenessItem>(\n items: readonly T[],\n): (T & { circulating?: boolean })[] {\n const supersededIds = new Set<string>();\n for (const item of items) {\n if (item.supersedes) supersededIds.add(item.supersedes);\n }\n return items.map((item) =>\n supersededIds.has(item.id) ? { ...item, circulating: true } : item,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,UAAU,SAAS,YAAY,WAAW,MAAM,QAAQ,UAAU;AAClF,OAAO,UAAU;AACjB,SAAS,SAAS;;;ACcX,SAAS,wBACd,GACA,GACyB;AACzB,MAAI,EAAE,O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,IAAI,MAAM,GAAG,QAAQ,IAAI,uBAAuB;AAExF,UAAM,iBAAiB,KAAK,KAAK,KAAK,eAAe,GAAG,IAAI,KAAK;AACjE,UAAM,gBAAgB,gBAAgB,OAAO;AAE7C,QAAI,KAAK,4CAA4C,cAAc,EAAE;AACrE,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,kBAAkB,aAAa;AAAA,MAC/B,0BAA0B,aAAa;AAAA,MACvC,cAAc,aAAa;AAAA,IAC7B;AAAA,EACF;AACF;","names":[]}
|
|
@@ -44,6 +44,14 @@ function parseSharedEnvelope(raw) {
|
|
|
44
44
|
const authority = requested.kind === "valid" ? requested.authority : "informational";
|
|
45
45
|
return withOptionalFields(authority, record);
|
|
46
46
|
}
|
|
47
|
+
function isExpired(envelope, nowMs) {
|
|
48
|
+
if (!Number.isFinite(nowMs)) return false;
|
|
49
|
+
const expiresAt = envelope.expiresAt?.trim();
|
|
50
|
+
if (!expiresAt) return false;
|
|
51
|
+
const expiresAtMs = Date.parse(expiresAt);
|
|
52
|
+
if (!Number.isFinite(expiresAtMs)) return false;
|
|
53
|
+
return expiresAtMs <= nowMs;
|
|
54
|
+
}
|
|
47
55
|
|
|
48
56
|
// src/shared-context/authority-precedence.ts
|
|
49
57
|
function isKnownAuthority(value) {
|
|
@@ -203,6 +211,8 @@ function resolveReadAuthority(envelope, allowBinding) {
|
|
|
203
211
|
}
|
|
204
212
|
|
|
205
213
|
export {
|
|
214
|
+
isExpired,
|
|
215
|
+
isStrictIsoInstant,
|
|
206
216
|
UNATTRIBUTED_ACCESS_WRITE_ORIGIN,
|
|
207
217
|
resolveWriteOrigin,
|
|
208
218
|
composeWriteEnvelope,
|
|
@@ -210,4 +220,4 @@ export {
|
|
|
210
220
|
envelopeFromScalars,
|
|
211
221
|
resolveReadAuthority
|
|
212
222
|
};
|
|
213
|
-
//# sourceMappingURL=chunk-
|
|
223
|
+
//# sourceMappingURL=chunk-OGXXGHW6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/shared-context/governance.ts","../src/shared-context/authority-precedence.ts","../src/shared-context/envelope-actor.ts","../src/shared-context/iso-instant.ts","../src/shared-context/envelope-at.ts","../src/shared-context/envelope-id.ts","../src/shared-context/envelope-io.ts"],"sourcesContent":["/**\n * Shared-item authority envelope (issue #1957).\n *\n * Pure parse/default/expiry helpers over the authority classes. Binding is\n * never inferred, and the authority token is validated exactly as supplied\n * or stored — a padded value never resolves to a privileged class.\n */\n\nexport const SHARED_AUTHORITIES = [\"informational\", \"advisory\", \"binding\"] as const;\nexport type SharedAuthority = (typeof SHARED_AUTHORITIES)[number];\n\nexport interface SharedEnvelope {\n sharedBy?: string;\n authority: SharedAuthority;\n expiresAt?: string;\n supersedes?: string;\n}\n\nexport interface SharedEnvelopeInput {\n sharedBy?: string;\n authority?: string;\n expiresAt?: string;\n supersedes?: string;\n}\n\nexport interface ApplyDefaultEnvelopeOptions {\n binding?: boolean;\n}\n\nfunction isSharedAuthority(value: string): value is SharedAuthority {\n return (SHARED_AUTHORITIES as readonly string[]).includes(value);\n}\n\nfunction optionalString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\ntype AuthorityToken =\n | { kind: \"absent\" }\n | { kind: \"invalid\"; raw: string }\n | { kind: \"valid\"; authority: SharedAuthority };\n\n/**\n * Read the authority token EXACTLY as supplied or stored. A padded value\n * such as `\" binding \"` is malformed data, never a normalized match for a\n * privileged class: trimming first would let stored whitespace resolve as\n * binding/advisory (AGENTS.md rule 45). Only the empty string counts as\n * \"unspecified\"; whitespace-only is invalid.\n */\nfunction readExactAuthority(value: unknown): AuthorityToken {\n if (typeof value !== \"string\" || value.length === 0) return { kind: \"absent\" };\n if (!isSharedAuthority(value)) return { kind: \"invalid\", raw: value };\n return { kind: \"valid\", authority: value };\n}\n\nfunction withOptionalFields(\n authority: SharedAuthority,\n source: { sharedBy?: unknown; expiresAt?: unknown; supersedes?: unknown },\n): SharedEnvelope {\n const envelope: SharedEnvelope = { authority };\n const sharedBy = optionalString(source.sharedBy);\n const expiresAt = optionalString(source.expiresAt);\n const supersedes = optionalString(source.supersedes);\n if (sharedBy) envelope.sharedBy = sharedBy;\n if (expiresAt) envelope.expiresAt = expiresAt;\n if (supersedes) envelope.supersedes = supersedes;\n return envelope;\n}\n\nexport function applyDefaultEnvelope(\n input: SharedEnvelopeInput = {},\n options: ApplyDefaultEnvelopeOptions = {},\n): SharedEnvelope {\n const requested = readExactAuthority(input.authority);\n if (requested.kind === \"invalid\") {\n throw new Error(\n `applyDefaultEnvelope: authority must be informational, advisory, or binding; got ${JSON.stringify(requested.raw)}`,\n );\n }\n if (requested.kind === \"valid\" && requested.authority === \"binding\" && options.binding !== true) {\n throw new Error(\"applyDefaultEnvelope: authority \\\"binding\\\" requires an explicit binding flag\");\n }\n return withOptionalFields(requested.kind === \"valid\" ? requested.authority : \"informational\", input);\n}\n\nexport function parseSharedEnvelope(raw: unknown): SharedEnvelope {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return { authority: \"informational\" };\n }\n const record = raw as Record<string, unknown>;\n const requested = readExactAuthority(record.authority);\n const authority = requested.kind === \"valid\" ? requested.authority : \"informational\";\n return withOptionalFields(authority, record);\n}\n\nexport function isExpired(envelope: Pick<SharedEnvelope, \"expiresAt\">, nowMs: number): boolean {\n if (!Number.isFinite(nowMs)) return false;\n const expiresAt = envelope.expiresAt?.trim();\n if (!expiresAt) return false;\n const expiresAtMs = Date.parse(expiresAt);\n if (!Number.isFinite(expiresAtMs)) return false;\n return expiresAtMs <= nowMs;\n}\n","/**\n * Shared-item authority precedence (issue #1957).\n *\n * Pure helpers over the authority classes owned by `governance.ts`\n * (`SHARED_AUTHORITIES`). Resolution is least-privilege: an absent,\n * malformed, or unrecognized authority never resolves above\n * `informational`, and `binding` additionally requires the explicit\n * `allowBinding` flag. The helpers are exported for callers; wiring them\n * into the shared-context read and write paths is a later slice.\n */\n\nimport { SHARED_AUTHORITIES, type SharedAuthority } from \"./governance.js\";\n\nexport { SHARED_AUTHORITIES as SHARED_AUTHORITY_CLASSES };\nexport type { SharedAuthority as SharedAuthorityClass };\n\nexport interface ResolveSharedAuthorityInput {\n /** Raw authority value from an item's envelope, if any. */\n authority?: unknown;\n /** Explicit opt-in required before \"binding\" is honored. */\n allowBinding?: boolean;\n}\n\nconst AUTHORITY_RANK: Readonly<Record<SharedAuthority, number>> = {\n informational: 0,\n advisory: 1,\n binding: 2,\n};\n\nfunction isKnownAuthority(value: string): value is SharedAuthority {\n return (SHARED_AUTHORITIES as readonly string[]).includes(value);\n}\n\n\nexport function resolveSharedAuthority(input: ResolveSharedAuthorityInput): SharedAuthority {\n // Read the security switch ONCE. A getter (or a Proxy) can return undefined\n // during validation and true at the decision, which would let binding\n // through without a validated opt-in.\n const allowBinding = input.allowBinding;\n if (allowBinding !== undefined && typeof allowBinding !== \"boolean\") {\n // The flag is the security switch, so a truthy string or number must\n // not enable binding: reject it instead of coercing.\n throw new TypeError(\n `resolveSharedAuthority: allowBinding must be a boolean when supplied, got ${typeof allowBinding}`,\n );\n }\n const authority = input.authority;\n // Absent (missing key, undefined, null) and present-but-invalid both land\n // on informational — the least-privileged class — so an unmarked or\n // malformed legacy item can never be treated as binding. Validate the\n // exact value: no trim, no case-fold, because \" binding\" and \"BINDING\"\n // are unrecognized data, not normalized matches for a known class.\n if (typeof authority !== \"string\") return \"informational\";\n if (!isKnownAuthority(authority)) return \"informational\";\n if (authority === \"binding\" && allowBinding !== true) {\n // Downgrade rather than throw: a legacy item already carrying \"binding\"\n // is stored data, not a caller bug, so it resolves to the highest class\n // that does not require the explicit opt-in.\n return \"advisory\";\n }\n return authority;\n}\n\nexport function compareSharedAuthority(a: string, b: string): number {\n const rankA = isKnownAuthority(a) ? AUTHORITY_RANK[a] : AUTHORITY_RANK.informational;\n const rankB = isKnownAuthority(b) ? AUTHORITY_RANK[b] : AUTHORITY_RANK.informational;\n return Math.sign(rankA - rankB);\n}\n","/**\n * Shared-item envelope actor parse (issue #1957 leftover).\n *\n * Pure. Empty is missing_actor. Newline is invalid_actor.\n */\n\nexport type ParseEnvelopeActorResult =\n | { ok: true; actor: string }\n | { ok: false; error: \"missing_actor\" | \"invalid_actor\" };\n\nexport function parseEnvelopeActor(value: string): ParseEnvelopeActorResult {\n const actor = value.trim();\n if (actor.length === 0) return { ok: false, error: \"missing_actor\" };\n if (actor.includes(\"\\n\")) return { ok: false, error: \"invalid_actor\" };\n return { ok: true, actor };\n}\n","/**\n * Strict ISO-8601 instant validation for shared-context envelopes\n * (issue #1957 review round 3).\n *\n * `Date.parse` is permissive: under the supported Node runtime it reads\n * `\"2026-02-30\"` as March 2 and `\"1\"` as January 1 2001. A caller-supplied\n * expiry would therefore be silently reinterpreted into a governance deadline\n * the caller never asked for. Validate the ISO shape AND the calendar\n * components against the exact input, and reject rather than normalize.\n *\n * Extracted from `provenance.ts` so the envelope write path and the\n * provenance stamp share one validator instead of two copies.\n */\n\n// Linear ISO instant. No nested quantifiers.\nconst ISO_INSTANT =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\n/**\n * True only for a calendar-valid ISO-8601 instant carrying an explicit zone.\n * Non-strings and non-finite parses are rejected explicitly, never coerced.\n */\nexport function isStrictIsoInstant(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n const match = ISO_INSTANT.exec(value);\n if (!match) return false;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const utc = new Date(Date.UTC(year, month - 1, day, hour, minute, second));\n return (\n Number.isFinite(Date.parse(value)) &&\n utc.getUTCFullYear() === year &&\n utc.getUTCMonth() === month - 1 &&\n utc.getUTCDate() === day &&\n utc.getUTCHours() === hour &&\n utc.getUTCMinutes() === minute &&\n utc.getUTCSeconds() === second\n );\n}\n","/**\n * Shared-item envelope at parse (issue #1957 leftover).\n *\n * Pure. Blank is missing_at. Anything that is not a calendar-valid ISO-8601\n * instant is invalid_at — including values permissive `Date.parse` would\n * silently reinterpret (`\"2026-02-30\"` -> March 2, `\"1\"` -> January 1 2001),\n * a whitespace-padded timestamp, and any non-string or non-finite input\n * (review round 3). `trim()` only detects blankness; validation reads the\n * exact value, so normalization can never widen what passes.\n */\n\nimport { isStrictIsoInstant } from \"./iso-instant.js\";\n\nexport type ParseEnvelopeAtResult =\n | { ok: true; at: string }\n | { ok: false; error: \"missing_at\" | \"invalid_at\" };\n\nexport function parseEnvelopeAt(value: string): ParseEnvelopeAtResult {\n if (typeof value !== \"string\") return { ok: false, error: \"invalid_at\" };\n if (value.trim().length === 0) return { ok: false, error: \"missing_at\" };\n if (!isStrictIsoInstant(value)) return { ok: false, error: \"invalid_at\" };\n return { ok: true, at: new Date(Date.parse(value)).toISOString() };\n}\n","/**\n * Shared-item envelope id parse (issue #1957 leftover).\n *\n * Pure. Empty is missing_id. Newline is invalid_id.\n */\n\nexport type ParseEnvelopeIdResult =\n | { ok: true; id: string }\n | { ok: false; error: \"missing_id\" | \"invalid_id\" };\n\nexport function parseEnvelopeId(value: string): ParseEnvelopeIdResult {\n const id = value.trim();\n if (id.length === 0) return { ok: false, error: \"missing_id\" };\n if (id.includes(\"\\n\")) return { ok: false, error: \"invalid_id\" };\n return { ok: true, id };\n}\n","/**\n * Shared-item envelope wiring (issue #1957, control 1: origin + authority).\n *\n * Bridges the pure envelope helpers onto the markdown frontmatter the\n * shared-context manager reads and writes.\n *\n * Write side rejects invalid input (an unrecognized authority or a binding\n * request without the config opt-in throws — never silently reinterpreted).\n * Read side resolves least privilege: a missing, malformed, or unrecognized\n * authority never resolves above informational, and stored binding\n * downgrades to advisory unless config opted in.\n */\n\nimport { applyDefaultEnvelope, parseSharedEnvelope, type SharedEnvelope } from \"./governance.js\";\nimport { resolveSharedAuthority } from \"./authority-precedence.js\";\nimport type { SharedAuthority } from \"./governance.js\";\nimport { parseEnvelopeActor } from \"./envelope-actor.js\";\nimport { parseEnvelopeAt } from \"./envelope-at.js\";\nimport { parseEnvelopeId } from \"./envelope-id.js\";\n\nexport interface ComposeWriteEnvelopeInput {\n /** Governance origin. Becomes the envelope's `sharedBy`. */\n origin: string;\n /** Requested authority class. Unrecognized values throw. */\n authority?: string;\n /** Optional ISO-8601 expiry. Invalid timestamps throw. */\n expiresAt?: string;\n /** Optional id of the item this one supersedes. */\n supersedes?: string;\n /** Config opt-in (`sharedContextAllowBindingAuthority`). Binding throws without it. */\n allowBinding: boolean;\n /**\n * Write instant for the expiry TTL policy (issue #2920). When finite, an\n * `expiresAt` must land strictly after it and within the maximum TTL —\n * a past or effectively-immortal expiry is a client input error, never a\n * silently accepted stamp.\n */\n nowMs?: number;\n}\n\nfunction requireEnvelopeActor(agentId: string): string {\n const parsed = parseEnvelopeActor(agentId);\n if (!parsed.ok) {\n throw new Error(`composeWriteEnvelope: agentId must be a non-blank single-line string (${parsed.error})`);\n }\n return parsed.actor;\n}\n\nfunction optionalEnvelopeAt(expiresAt: string | undefined): string | undefined {\n if (expiresAt === undefined) return undefined;\n const parsed = parseEnvelopeAt(expiresAt);\n if (!parsed.ok) {\n throw new Error(`composeWriteEnvelope: expiresAt must be a valid ISO-8601 timestamp (${parsed.error})`);\n }\n return parsed.at;\n}\n\n/** Maximum write-side TTL: 10 years. A farther `expiresAt` is rejected. */\nexport const MAX_WRITE_EXPIRES_AT_TTL_MS = 3650 * 24 * 60 * 60 * 1000;\n\nfunction assertBoundedFutureExpiry(expiresAt: string, nowMs: number): void {\n const expiresAtMs = Date.parse(expiresAt);\n if (expiresAtMs <= nowMs) {\n throw new Error(\"composeWriteEnvelope: expiresAt must be an instant strictly after the write time\");\n }\n if (expiresAtMs - nowMs > MAX_WRITE_EXPIRES_AT_TTL_MS) {\n throw new Error(\n `composeWriteEnvelope: expiresAt exceeds the maximum TTL of ${MAX_WRITE_EXPIRES_AT_TTL_MS}ms`,\n );\n }\n}\n\nfunction optionalEnvelopeId(supersedes: string | undefined): string | undefined {\n if (supersedes === undefined) return undefined;\n const parsed = parseEnvelopeId(supersedes);\n if (!parsed.ok) {\n throw new Error(`composeWriteEnvelope: supersedes must be a non-blank single-line id (${parsed.error})`);\n }\n return parsed.id;\n}\n\n/**\n * Reserved governance origin for an authenticated external access write that\n * resolved no principal (`agentAccessHttp.principal` unset, no adapter\n * identity). Server-owned: the caller cannot mint or influence it, and the\n * caller-supplied `agentId` never becomes audit metadata on that path.\n */\nexport const UNATTRIBUTED_ACCESS_WRITE_ORIGIN = \"unattributed:access-surface\";\n\nexport interface ResolvedWriteIdentity {\n /**\n * Producer identity: frontmatter `agent`, on-disk segment, and the\n * cross-signals grouping key. Self-declared by the caller only on\n * surfaces that resolved no server identity; never decides authority.\n */\n agent: string;\n /** Governance origin stamped as the envelope's `sharedBy`. */\n origin: string;\n}\n\n/**\n * Resolve the producer identity and governance origin for a shared-context\n * write. They are different fields with different trust requirements:\n *\n * - The origin (`sharedBy`) is audit metadata and is always server-derived.\n * When the surface resolved an authenticated identity, that identity IS the\n * origin; when it resolved none but the write crosses an external\n * boundary, the caller-supplied `unattributedOrigin` token is stamped\n * instead — never the caller's value. Only a trusted in-process caller\n * (no identity, no token) may stamp its own id as the origin.\n * - The producer (`agent`) drives grouping and display only. When an\n * authenticated identity exists it is also the producer, and a\n * caller-supplied `agentId` naming a different agent is REJECTED, so a\n * caller can never publish an item attributed to another agent. Without a\n * server identity the caller's label stands as the producer — collapsing\n * it instead would merge every writer into one agent and erase\n * multi-agent overlaps from `synthesizeCrossSignals`.\n */\nexport function resolveWriteOrigin(input: {\n agentId: string;\n authenticatedIdentity?: string;\n unattributedOrigin?: string;\n}): ResolvedWriteIdentity {\n const identity = input.authenticatedIdentity?.trim() ?? \"\";\n if (identity.length > 0) {\n const requested = input.agentId.trim();\n if (requested.length > 0 && requested !== identity) {\n throw new Error(\n `shared-context write origin mismatch: authenticated identity ${JSON.stringify(identity)} cannot publish as ${JSON.stringify(requested)}`,\n );\n }\n return { agent: identity, origin: identity };\n }\n const unattributed = input.unattributedOrigin?.trim() ?? \"\";\n if (unattributed.length > 0) {\n const label = input.agentId.trim();\n return {\n agent: label.length > 0 ? requireProducer(label) : requireProducer(unattributed),\n origin: requireProducer(unattributed),\n };\n }\n const actor = requireProducer(input.agentId);\n return { agent: actor, origin: actor };\n}\n\nfunction requireProducer(value: string): string {\n const parsed = parseEnvelopeActor(value);\n if (!parsed.ok) {\n throw new Error(`shared-context write producer must be a non-blank single-line string (${parsed.error})`);\n }\n return parsed.actor;\n}\n\n/**\n * Validate and compose the envelope for a shared-context write.\n * `sharedBy` is stamped from the server-derived origin — provenance is\n * never injected through item content or the caller's producer label.\n */\nexport function composeWriteEnvelope(input: ComposeWriteEnvelopeInput): SharedEnvelope {\n const sharedBy = requireEnvelopeActor(input.origin);\n const expiresAt = optionalEnvelopeAt(input.expiresAt);\n if (expiresAt !== undefined && Number.isFinite(input.nowMs ?? Number.NaN)) {\n assertBoundedFutureExpiry(expiresAt, input.nowMs as number);\n }\n const supersedes = optionalEnvelopeId(input.supersedes);\n return applyDefaultEnvelope(\n { sharedBy, authority: input.authority, expiresAt, supersedes },\n { binding: input.allowBinding },\n );\n}\n\n/** Serialize an envelope into frontmatter lines (caller adds the `---` fences). */\nexport function envelopeToFrontmatterLines(envelope: SharedEnvelope): string[] {\n const line = (key: string, value: string) => `${key}: ${JSON.stringify(value)}`;\n const lines = [line(\"sharedBy\", envelope.sharedBy ?? \"\"), line(\"authority\", envelope.authority)];\n if (envelope.expiresAt !== undefined) lines.push(line(\"expiresAt\", envelope.expiresAt));\n if (envelope.supersedes !== undefined) lines.push(line(\"supersedes\", envelope.supersedes));\n return lines;\n}\n\n/**\n * Build an envelope from frontmatter scalars already read off a stored item.\n * Missing scalars (legacy items) compose to informational with no expiry.\n */\nexport function envelopeFromScalars(scalars: {\n sharedBy: string | null;\n authority: string | null;\n expiresAt: string | null;\n supersedes: string | null;\n}): SharedEnvelope {\n const record: Record<string, string> = {};\n if (scalars.sharedBy !== null) record.sharedBy = scalars.sharedBy;\n if (scalars.authority !== null) record.authority = scalars.authority;\n if (scalars.expiresAt !== null) record.expiresAt = scalars.expiresAt;\n if (scalars.supersedes !== null) record.supersedes = scalars.supersedes;\n return parseSharedEnvelope(record);\n}\n\n/**\n * Resolve a stored envelope's authority for read-side consumption.\n * Least privilege: unrecognized/missing stays informational; binding\n * requires the config opt-in or downgrades to advisory.\n */\nexport function resolveReadAuthority(\n envelope: Pick<SharedEnvelope, \"authority\">,\n allowBinding: boolean,\n): SharedAuthority {\n return resolveSharedAuthority({ authority: envelope.authority, allowBinding });\n}\n"],"mappings":";AAQO,IAAM,qBAAqB,CAAC,iBAAiB,YAAY,SAAS;AAqBzE,SAAS,kBAAkB,OAAyC;AAClE,SAAQ,mBAAyC,SAAS,KAAK;AACjE;AAEA,SAAS,eAAe,OAAoC;AAC1D,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAcA,SAAS,mBAAmB,OAAgC;AAC1D,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW,EAAG,QAAO,EAAE,MAAM,SAAS;AAC7E,MAAI,CAAC,kBAAkB,KAAK,EAAG,QAAO,EAAE,MAAM,WAAW,KAAK,MAAM;AACpE,SAAO,EAAE,MAAM,SAAS,WAAW,MAAM;AAC3C;AAEA,SAAS,mBACP,WACA,QACgB;AAChB,QAAM,WAA2B,EAAE,UAAU;AAC7C,QAAM,WAAW,eAAe,OAAO,QAAQ;AAC/C,QAAM,YAAY,eAAe,OAAO,SAAS;AACjD,QAAM,aAAa,eAAe,OAAO,UAAU;AACnD,MAAI,SAAU,UAAS,WAAW;AAClC,MAAI,UAAW,UAAS,YAAY;AACpC,MAAI,WAAY,UAAS,aAAa;AACtC,SAAO;AACT;AAEO,S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M,QAAQ,CAAC,KAAK,YAAY,SAAS,YAAY,EAAE,GAAG,KAAK,aAAa,SAAS,SAAS,CAAC;AAC/F,MAAI,SAAS,cAAc,OAAW,OAAM,KAAK,KAAK,aAAa,SAAS,SAAS,CAAC;AACtF,MAAI,SAAS,eAAe,OAAW,OAAM,KAAK,KAAK,cAAc,SAAS,UAAU,CAAC;AACzF,SAAO;AACT;AAMO,SAAS,oBAAoB,SAKjB;AACjB,QAAM,SAAiC,CAAC;AACxC,MAAI,QAAQ,aAAa,KAAM,QAAO,WAAW,QAAQ;AACzD,MAAI,QAAQ,cAAc,KAAM,QAAO,YAAY,QAAQ;AAC3D,MAAI,QAAQ,cAAc,KAAM,QAAO,YAAY,QAAQ;AAC3D,MAAI,QAAQ,eAAe,KAAM,QAAO,aAAa,QAAQ;AAC7D,SAAO,oBAAoB,MAAM;AACnC;AAOO,SAAS,qBACd,UACA,cACiB;AACjB,SAAO,uBAAuB,EAAE,WAAW,SAAS,WAAW,aAAa,CAAC;AAC/E;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/shared-context/governance.ts","../src/shared-context/authority-precedence.ts","../src/shared-context/envelope-actor.ts","../src/shared-context/iso-instant.ts","../src/shared-context/envelope-at.ts","../src/shared-context/envelope-id.ts","../src/shared-context/envelope-io.ts"],"sourcesContent":["/**\n * Shared-item authority envelope (issue #1957).\n *\n * Pure parse/default/expiry helpers over the authority classes. Binding is\n * never inferred, and the authority token is validated exactly as supplied\n * or stored — a padded value never resolves to a privileged class.\n */\n\nexport const SHARED_AUTHORITIES = [\"informational\", \"advisory\", \"binding\"] as const;\nexport type SharedAuthority = (typeof SHARED_AUTHORITIES)[number];\n\nexport interface SharedEnvelope {\n sharedBy?: string;\n authority: SharedAuthority;\n expiresAt?: string;\n supersedes?: string;\n}\n\nexport interface SharedEnvelopeInput {\n sharedBy?: string;\n authority?: string;\n expiresAt?: string;\n supersedes?: string;\n}\n\nexport interface ApplyDefaultEnvelopeOptions {\n binding?: boolean;\n}\n\nfunction isSharedAuthority(value: string): value is SharedAuthority {\n return (SHARED_AUTHORITIES as readonly string[]).includes(value);\n}\n\nfunction optionalString(value: unknown): string | undefined {\n if (typeof value !== \"string\") return undefined;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\ntype AuthorityToken =\n | { kind: \"absent\" }\n | { kind: \"invalid\"; raw: string }\n | { kind: \"valid\"; authority: SharedAuthority };\n\n/**\n * Read the authority token EXACTLY as supplied or stored. A padded value\n * such as `\" binding \"` is malformed data, never a normalized match for a\n * privileged class: trimming first would let stored whitespace resolve as\n * binding/advisory (AGENTS.md rule 45). Only the empty string counts as\n * \"unspecified\"; whitespace-only is invalid.\n */\nfunction readExactAuthority(value: unknown): AuthorityToken {\n if (typeof value !== \"string\" || value.length === 0) return { kind: \"absent\" };\n if (!isSharedAuthority(value)) return { kind: \"invalid\", raw: value };\n return { kind: \"valid\", authority: value };\n}\n\nfunction withOptionalFields(\n authority: SharedAuthority,\n source: { sharedBy?: unknown; expiresAt?: unknown; supersedes?: unknown },\n): SharedEnvelope {\n const envelope: SharedEnvelope = { authority };\n const sharedBy = optionalString(source.sharedBy);\n const expiresAt = optionalString(source.expiresAt);\n const supersedes = optionalString(source.supersedes);\n if (sharedBy) envelope.sharedBy = sharedBy;\n if (expiresAt) envelope.expiresAt = expiresAt;\n if (supersedes) envelope.supersedes = supersedes;\n return envelope;\n}\n\nexport function applyDefaultEnvelope(\n input: SharedEnvelopeInput = {},\n options: ApplyDefaultEnvelopeOptions = {},\n): SharedEnvelope {\n const requested = readExactAuthority(input.authority);\n if (requested.kind === \"invalid\") {\n throw new Error(\n `applyDefaultEnvelope: authority must be informational, advisory, or binding; got ${JSON.stringify(requested.raw)}`,\n );\n }\n if (requested.kind === \"valid\" && requested.authority === \"binding\" && options.binding !== true) {\n throw new Error(\"applyDefaultEnvelope: authority \\\"binding\\\" requires an explicit binding flag\");\n }\n return withOptionalFields(requested.kind === \"valid\" ? requested.authority : \"informational\", input);\n}\n\nexport function parseSharedEnvelope(raw: unknown): SharedEnvelope {\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n return { authority: \"informational\" };\n }\n const record = raw as Record<string, unknown>;\n const requested = readExactAuthority(record.authority);\n const authority = requested.kind === \"valid\" ? requested.authority : \"informational\";\n return withOptionalFields(authority, record);\n}\n\nexport function isExpired(envelope: Pick<SharedEnvelope, \"expiresAt\">, nowMs: number): boolean {\n if (!Number.isFinite(nowMs)) return false;\n const expiresAt = envelope.expiresAt?.trim();\n if (!expiresAt) return false;\n const expiresAtMs = Date.parse(expiresAt);\n if (!Number.isFinite(expiresAtMs)) return false;\n return expiresAtMs <= nowMs;\n}\n","/**\n * Shared-item authority precedence (issue #1957).\n *\n * Pure helpers over the authority classes owned by `governance.ts`\n * (`SHARED_AUTHORITIES`). Resolution is least-privilege: an absent,\n * malformed, or unrecognized authority never resolves above\n * `informational`, and `binding` additionally requires the explicit\n * `allowBinding` flag. The helpers are exported for callers; wiring them\n * into the shared-context read and write paths is a later slice.\n */\n\nimport { SHARED_AUTHORITIES, type SharedAuthority } from \"./governance.js\";\n\nexport { SHARED_AUTHORITIES as SHARED_AUTHORITY_CLASSES };\nexport type { SharedAuthority as SharedAuthorityClass };\n\nexport interface ResolveSharedAuthorityInput {\n /** Raw authority value from an item's envelope, if any. */\n authority?: unknown;\n /** Explicit opt-in required before \"binding\" is honored. */\n allowBinding?: boolean;\n}\n\nconst AUTHORITY_RANK: Readonly<Record<SharedAuthority, number>> = {\n informational: 0,\n advisory: 1,\n binding: 2,\n};\n\nfunction isKnownAuthority(value: string): value is SharedAuthority {\n return (SHARED_AUTHORITIES as readonly string[]).includes(value);\n}\n\n\nexport function resolveSharedAuthority(input: ResolveSharedAuthorityInput): SharedAuthority {\n // Read the security switch ONCE. A getter (or a Proxy) can return undefined\n // during validation and true at the decision, which would let binding\n // through without a validated opt-in.\n const allowBinding = input.allowBinding;\n if (allowBinding !== undefined && typeof allowBinding !== \"boolean\") {\n // The flag is the security switch, so a truthy string or number must\n // not enable binding: reject it instead of coercing.\n throw new TypeError(\n `resolveSharedAuthority: allowBinding must be a boolean when supplied, got ${typeof allowBinding}`,\n );\n }\n const authority = input.authority;\n // Absent (missing key, undefined, null) and present-but-invalid both land\n // on informational — the least-privileged class — so an unmarked or\n // malformed legacy item can never be treated as binding. Validate the\n // exact value: no trim, no case-fold, because \" binding\" and \"BINDING\"\n // are unrecognized data, not normalized matches for a known class.\n if (typeof authority !== \"string\") return \"informational\";\n if (!isKnownAuthority(authority)) return \"informational\";\n if (authority === \"binding\" && allowBinding !== true) {\n // Downgrade rather than throw: a legacy item already carrying \"binding\"\n // is stored data, not a caller bug, so it resolves to the highest class\n // that does not require the explicit opt-in.\n return \"advisory\";\n }\n return authority;\n}\n\nexport function compareSharedAuthority(a: string, b: string): number {\n const rankA = isKnownAuthority(a) ? AUTHORITY_RANK[a] : AUTHORITY_RANK.informational;\n const rankB = isKnownAuthority(b) ? AUTHORITY_RANK[b] : AUTHORITY_RANK.informational;\n return Math.sign(rankA - rankB);\n}\n","/**\n * Shared-item envelope actor parse (issue #1957 leftover).\n *\n * Pure. Empty is missing_actor. Newline is invalid_actor.\n */\n\nexport type ParseEnvelopeActorResult =\n | { ok: true; actor: string }\n | { ok: false; error: \"missing_actor\" | \"invalid_actor\" };\n\nexport function parseEnvelopeActor(value: string): ParseEnvelopeActorResult {\n const actor = value.trim();\n if (actor.length === 0) return { ok: false, error: \"missing_actor\" };\n if (actor.includes(\"\\n\")) return { ok: false, error: \"invalid_actor\" };\n return { ok: true, actor };\n}\n","/**\n * Strict ISO-8601 instant validation for shared-context envelopes\n * (issue #1957 review round 3).\n *\n * `Date.parse` is permissive: under the supported Node runtime it reads\n * `\"2026-02-30\"` as March 2 and `\"1\"` as January 1 2001. A caller-supplied\n * expiry would therefore be silently reinterpreted into a governance deadline\n * the caller never asked for. Validate the ISO shape AND the calendar\n * components against the exact input, and reject rather than normalize.\n *\n * Extracted from `provenance.ts` so the envelope write path and the\n * provenance stamp share one validator instead of two copies.\n */\n\n// Linear ISO instant. No nested quantifiers.\nconst ISO_INSTANT =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\n/**\n * True only for a calendar-valid ISO-8601 instant carrying an explicit zone.\n * Non-strings and non-finite parses are rejected explicitly, never coerced.\n */\nexport function isStrictIsoInstant(value: unknown): boolean {\n if (typeof value !== \"string\") return false;\n const match = ISO_INSTANT.exec(value);\n if (!match) return false;\n const year = Number(match[1]);\n const month = Number(match[2]);\n const day = Number(match[3]);\n const hour = Number(match[4]);\n const minute = Number(match[5]);\n const second = Number(match[6]);\n const utc = new Date(Date.UTC(year, month - 1, day, hour, minute, second));\n return (\n Number.isFinite(Date.parse(value)) &&\n utc.getUTCFullYear() === year &&\n utc.getUTCMonth() === month - 1 &&\n utc.getUTCDate() === day &&\n utc.getUTCHours() === hour &&\n utc.getUTCMinutes() === minute &&\n utc.getUTCSeconds() === second\n );\n}\n","/**\n * Shared-item envelope at parse (issue #1957 leftover).\n *\n * Pure. Blank is missing_at. Anything that is not a calendar-valid ISO-8601\n * instant is invalid_at — including values permissive `Date.parse` would\n * silently reinterpret (`\"2026-02-30\"` -> March 2, `\"1\"` -> January 1 2001),\n * a whitespace-padded timestamp, and any non-string or non-finite input\n * (review round 3). `trim()` only detects blankness; validation reads the\n * exact value, so normalization can never widen what passes.\n */\n\nimport { isStrictIsoInstant } from \"./iso-instant.js\";\n\nexport type ParseEnvelopeAtResult =\n | { ok: true; at: string }\n | { ok: false; error: \"missing_at\" | \"invalid_at\" };\n\nexport function parseEnvelopeAt(value: string): ParseEnvelopeAtResult {\n if (typeof value !== \"string\") return { ok: false, error: \"invalid_at\" };\n if (value.trim().length === 0) return { ok: false, error: \"missing_at\" };\n if (!isStrictIsoInstant(value)) return { ok: false, error: \"invalid_at\" };\n return { ok: true, at: new Date(Date.parse(value)).toISOString() };\n}\n","/**\n * Shared-item envelope id parse (issue #1957 leftover).\n *\n * Pure. Empty is missing_id. Newline is invalid_id.\n */\n\nexport type ParseEnvelopeIdResult =\n | { ok: true; id: string }\n | { ok: false; error: \"missing_id\" | \"invalid_id\" };\n\nexport function parseEnvelopeId(value: string): ParseEnvelopeIdResult {\n const id = value.trim();\n if (id.length === 0) return { ok: false, error: \"missing_id\" };\n if (id.includes(\"\\n\")) return { ok: false, error: \"invalid_id\" };\n return { ok: true, id };\n}\n","/**\n * Shared-item envelope wiring (issue #1957, control 1: origin + authority).\n *\n * Bridges the pure envelope helpers onto the markdown frontmatter the\n * shared-context manager reads and writes.\n *\n * Write side rejects invalid input (an unrecognized authority or a binding\n * request without the config opt-in throws — never silently reinterpreted).\n * Read side resolves least privilege: a missing, malformed, or unrecognized\n * authority never resolves above informational, and stored binding\n * downgrades to advisory unless config opted in.\n */\n\nimport { applyDefaultEnvelope, parseSharedEnvelope, type SharedEnvelope } from \"./governance.js\";\nimport { resolveSharedAuthority } from \"./authority-precedence.js\";\nimport type { SharedAuthority } from \"./governance.js\";\nimport { parseEnvelopeActor } from \"./envelope-actor.js\";\nimport { parseEnvelopeAt } from \"./envelope-at.js\";\nimport { parseEnvelopeId } from \"./envelope-id.js\";\n\nexport interface ComposeWriteEnvelopeInput {\n /** Governance origin. Becomes the envelope's `sharedBy`. */\n origin: string;\n /** Requested authority class. Unrecognized values throw. */\n authority?: string;\n /** Optional ISO-8601 expiry. Invalid timestamps throw. */\n expiresAt?: string;\n /** Optional id of the item this one supersedes. */\n supersedes?: string;\n /** Config opt-in (`sharedContextAllowBindingAuthority`). Binding throws without it. */\n allowBinding: boolean;\n /**\n * Write instant for the expiry TTL policy (issue #2920). When finite, an\n * `expiresAt` must land strictly after it and within the maximum TTL —\n * a past or effectively-immortal expiry is a client input error, never a\n * silently accepted stamp.\n */\n nowMs?: number;\n}\n\nfunction requireEnvelopeActor(agentId: string): string {\n const parsed = parseEnvelopeActor(agentId);\n if (!parsed.ok) {\n throw new Error(`composeWriteEnvelope: agentId must be a non-blank single-line string (${parsed.error})`);\n }\n return parsed.actor;\n}\n\nfunction optionalEnvelopeAt(expiresAt: string | undefined): string | undefined {\n if (expiresAt === undefined) return undefined;\n const parsed = parseEnvelopeAt(expiresAt);\n if (!parsed.ok) {\n throw new Error(`composeWriteEnvelope: expiresAt must be a valid ISO-8601 timestamp (${parsed.error})`);\n }\n return parsed.at;\n}\n\n/** Maximum write-side TTL: 10 years. A farther `expiresAt` is rejected. */\nexport const MAX_WRITE_EXPIRES_AT_TTL_MS = 3650 * 24 * 60 * 60 * 1000;\n\nfunction assertBoundedFutureExpiry(expiresAt: string, nowMs: number): void {\n const expiresAtMs = Date.parse(expiresAt);\n if (expiresAtMs <= nowMs) {\n throw new Error(\"composeWriteEnvelope: expiresAt must be an instant strictly after the write time\");\n }\n if (expiresAtMs - nowMs > MAX_WRITE_EXPIRES_AT_TTL_MS) {\n throw new Error(\n `composeWriteEnvelope: expiresAt exceeds the maximum TTL of ${MAX_WRITE_EXPIRES_AT_TTL_MS}ms`,\n );\n }\n}\n\nfunction optionalEnvelopeId(supersedes: string | undefined): string | undefined {\n if (supersedes === undefined) return undefined;\n const parsed = parseEnvelopeId(supersedes);\n if (!parsed.ok) {\n throw new Error(`composeWriteEnvelope: supersedes must be a non-blank single-line id (${parsed.error})`);\n }\n return parsed.id;\n}\n\n/**\n * Reserved governance origin for an authenticated external access write that\n * resolved no principal (`agentAccessHttp.principal` unset, no adapter\n * identity). Server-owned: the caller cannot mint or influence it, and the\n * caller-supplied `agentId` never becomes audit metadata on that path.\n */\nexport const UNATTRIBUTED_ACCESS_WRITE_ORIGIN = \"unattributed:access-surface\";\n\nexport interface ResolvedWriteIdentity {\n /**\n * Producer identity: frontmatter `agent`, on-disk segment, and the\n * cross-signals grouping key. Self-declared by the caller only on\n * surfaces that resolved no server identity; never decides authority.\n */\n agent: string;\n /** Governance origin stamped as the envelope's `sharedBy`. */\n origin: string;\n}\n\n/**\n * Resolve the producer identity and governance origin for a shared-context\n * write. They are different fields with different trust requirements:\n *\n * - The origin (`sharedBy`) is audit metadata and is always server-derived.\n * When the surface resolved an authenticated identity, that identity IS the\n * origin; when it resolved none but the write crosses an external\n * boundary, the caller-supplied `unattributedOrigin` token is stamped\n * instead — never the caller's value. Only a trusted in-process caller\n * (no identity, no token) may stamp its own id as the origin.\n * - The producer (`agent`) drives grouping and display only. When an\n * authenticated identity exists it is also the producer, and a\n * caller-supplied `agentId` naming a different agent is REJECTED, so a\n * caller can never publish an item attributed to another agent. Without a\n * server identity the caller's label stands as the producer — collapsing\n * it instead would merge every writer into one agent and erase\n * multi-agent overlaps from `synthesizeCrossSignals`.\n */\nexport function resolveWriteOrigin(input: {\n agentId: string;\n authenticatedIdentity?: string;\n unattributedOrigin?: string;\n}): ResolvedWriteIdentity {\n const identity = input.authenticatedIdentity?.trim() ?? \"\";\n if (identity.length > 0) {\n const requested = input.agentId.trim();\n if (requested.length > 0 && requested !== identity) {\n throw new Error(\n `shared-context write origin mismatch: authenticated identity ${JSON.stringify(identity)} cannot publish as ${JSON.stringify(requested)}`,\n );\n }\n return { agent: identity, origin: identity };\n }\n const unattributed = input.unattributedOrigin?.trim() ?? \"\";\n if (unattributed.length > 0) {\n const label = input.agentId.trim();\n return {\n agent: label.length > 0 ? requireProducer(label) : requireProducer(unattributed),\n origin: requireProducer(unattributed),\n };\n }\n const actor = requireProducer(input.agentId);\n return { agent: actor, origin: actor };\n}\n\nfunction requireProducer(value: string): string {\n const parsed = parseEnvelopeActor(value);\n if (!parsed.ok) {\n throw new Error(`shared-context write producer must be a non-blank single-line string (${parsed.error})`);\n }\n return parsed.actor;\n}\n\n/**\n * Validate and compose the envelope for a shared-context write.\n * `sharedBy` is stamped from the server-derived origin — provenance is\n * never injected through item content or the caller's producer label.\n */\nexport function composeWriteEnvelope(input: ComposeWriteEnvelopeInput): SharedEnvelope {\n const sharedBy = requireEnvelopeActor(input.origin);\n const expiresAt = optionalEnvelopeAt(input.expiresAt);\n if (expiresAt !== undefined && Number.isFinite(input.nowMs ?? Number.NaN)) {\n assertBoundedFutureExpiry(expiresAt, input.nowMs as number);\n }\n const supersedes = optionalEnvelopeId(input.supersedes);\n return applyDefaultEnvelope(\n { sharedBy, authority: input.authority, expiresAt, supersedes },\n { binding: input.allowBinding },\n );\n}\n\n/** Serialize an envelope into frontmatter lines (caller adds the `---` fences). */\nexport function envelopeToFrontmatterLines(envelope: SharedEnvelope): string[] {\n const line = (key: string, value: string) => `${key}: ${JSON.stringify(value)}`;\n const lines = [line(\"sharedBy\", envelope.sharedBy ?? \"\"), line(\"authority\", envelope.authority)];\n if (envelope.expiresAt !== undefined) lines.push(line(\"expiresAt\", envelope.expiresAt));\n if (envelope.supersedes !== undefined) lines.push(line(\"supersedes\", envelope.supersedes));\n return lines;\n}\n\n/**\n * Build an envelope from frontmatter scalars already read off a stored item.\n * Missing scalars (legacy items) compose to informational with no expiry.\n */\nexport function envelopeFromScalars(scalars: {\n sharedBy: string | null;\n authority: string | null;\n expiresAt: string | null;\n supersedes: string | null;\n}): SharedEnvelope {\n const record: Record<string, string> = {};\n if (scalars.sharedBy !== null) record.sharedBy = scalars.sharedBy;\n if (scalars.authority !== null) record.authority = scalars.authority;\n if (scalars.expiresAt !== null) record.expiresAt = scalars.expiresAt;\n if (scalars.supersedes !== null) record.supersedes = scalars.supersedes;\n return parseSharedEnvelope(record);\n}\n\n/**\n * Resolve a stored envelope's authority for read-side consumption.\n * Least privilege: unrecognized/missing stays informational; binding\n * requires the config opt-in or downgrades to advisory.\n */\nexport function resolveReadAuthority(\n envelope: Pick<SharedEnvelope, \"authority\">,\n allowBinding: boolean,\n): SharedAuthority {\n return resolveSharedAuthority({ authority: envelope.authority, allowBinding });\n}\n"],"mappings":";AAQO,IAAM,qBAAqB,CAAC,iBAAiB,YAAY,SAAS;AAqBzE,SAAS,kBAAkB,OAAyC;AAClE,SAAQ,mBAAyC,SAAS,KAAK;AACjE;AAEA,SAAS,eA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AW,QAAQ;AACzD,MAAI,QAAQ,cAAc,KAAM,QAAO,YAAY,QAAQ;AAC3D,MAAI,QAAQ,cAAc,KAAM,QAAO,YAAY,QAAQ;AAC3D,MAAI,QAAQ,eAAe,KAAM,QAAO,aAAa,QAAQ;AAC7D,SAAO,oBAAoB,MAAM;AACnC;AAOO,SAAS,qBACd,UACA,cACiB;AACjB,SAAO,uBAAuB,EAAE,WAAW,SAAS,WAAW,aAAa,CAAC;AAC/E;","names":[]}
|
|
@@ -29,7 +29,7 @@ import {
|
|
|
29
29
|
defineOperation,
|
|
30
30
|
parseNamespacePreflightWriteOp,
|
|
31
31
|
resolveAuthorizedNamespaceWritablePreflight
|
|
32
|
-
} from "./chunk-
|
|
32
|
+
} from "./chunk-ZBYVR5W4.js";
|
|
33
33
|
import {
|
|
34
34
|
parseSharedWriteOutputControls
|
|
35
35
|
} from "./chunk-IFBSZGW3.js";
|
|
@@ -594,4 +594,4 @@ defineOperation({ name: "graph_events", description: "SSE graph events.", schema
|
|
|
594
594
|
defineOperation({ name: "chat_message", description: "Chat message.", schema: strictSchema({ message: S.str, chatSessionId: S.str }), handler: async (_i, _ctx) => ({ result: { ok: true } }) });
|
|
595
595
|
defineOperation({ name: "chat_events", description: "SSE chat events.", schema: strictSchema({}), handler: async (_i, _ctx) => ({ result: { stream: "sse" } }) });
|
|
596
596
|
defineOperation({ name: "adapters_status", description: "Adapter registry metadata (issue #1850 round 5). Marker op: the HTTP transport builds the response from its own adapterRegistry, but the op still must be registered so it appears in listRegisteredOperations and enforceTokenOp can gate it for scoped tokens.", schema: strictSchema({}), handler: async (_i, _ctx) => ({ result: { ok: true } }) });
|
|
597
|
-
//# sourceMappingURL=chunk-
|
|
597
|
+
//# sourceMappingURL=chunk-TJNDFNCU.js.map
|