dsh-agent-memory-hub 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client.js +103 -0
- package/dist/index.js +823 -5
- package/dist/index.js.map +4 -4
- package/package.json +13 -2
package/dist/index.js
CHANGED
|
@@ -67,7 +67,29 @@ function parseIso(value) {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
// ../../dist/core/ids.js
|
|
70
|
+
var PREFIX = {
|
|
71
|
+
decision: "DEC",
|
|
72
|
+
constraint: "CON",
|
|
73
|
+
knowledge: "KNO",
|
|
74
|
+
"api-catalog": "API",
|
|
75
|
+
process: "PRC",
|
|
76
|
+
"open-questions": "OPQ",
|
|
77
|
+
"runtime-base": "RTB",
|
|
78
|
+
playbooks: "PLB",
|
|
79
|
+
assets: "AST"
|
|
80
|
+
};
|
|
70
81
|
var PENDING_PREFIX = "PRO";
|
|
82
|
+
function prefixFor(type) {
|
|
83
|
+
return PREFIX[type];
|
|
84
|
+
}
|
|
85
|
+
function nextKnowledgeId(seqDir, type, readSequences2, writeSequences2) {
|
|
86
|
+
const prefix = prefixFor(type);
|
|
87
|
+
const seq = readSequences2(seqDir);
|
|
88
|
+
const next = (seq[prefix] ?? 0) + 1;
|
|
89
|
+
seq[prefix] = next;
|
|
90
|
+
writeSequences2(seqDir, seq);
|
|
91
|
+
return `${prefix}-${String(next).padStart(6, "0")}`;
|
|
92
|
+
}
|
|
71
93
|
function nextProposalId(seqDir, readSequences2, writeSequences2) {
|
|
72
94
|
const seq = readSequences2(seqDir);
|
|
73
95
|
const next = (seq[PENDING_PREFIX] ?? 0) + 1;
|
|
@@ -106,6 +128,7 @@ function atomicWrite(filePath, content) {
|
|
|
106
128
|
}
|
|
107
129
|
|
|
108
130
|
// ../../dist/core/hub.js
|
|
131
|
+
var HUB_CONFIG = "hub.yaml";
|
|
109
132
|
var LEDGER_FILE = "records/ledger.jsonl";
|
|
110
133
|
var SEQUENCES_FILE = "records/sequences.json";
|
|
111
134
|
var LOCK_FILE = ".writer.lock";
|
|
@@ -115,9 +138,32 @@ function isHubInitialized(root) {
|
|
|
115
138
|
function knowledgeDir(root, type) {
|
|
116
139
|
return (0, import_node_path2.join)(root, "knowledge", type);
|
|
117
140
|
}
|
|
141
|
+
function historyDir(root, type) {
|
|
142
|
+
return (0, import_node_path2.join)(root, "history", type);
|
|
143
|
+
}
|
|
118
144
|
function pendingDir(root) {
|
|
119
145
|
return (0, import_node_path2.join)(root, "pending");
|
|
120
146
|
}
|
|
147
|
+
function journalDir(root) {
|
|
148
|
+
return (0, import_node_path2.join)(root, "journal");
|
|
149
|
+
}
|
|
150
|
+
function readHubConfig(root) {
|
|
151
|
+
const path = (0, import_node_path2.join)(root, HUB_CONFIG);
|
|
152
|
+
if (!(0, import_node_fs2.existsSync)(path))
|
|
153
|
+
return {};
|
|
154
|
+
const raw = (0, import_node_fs2.readFileSync)(path, "utf8");
|
|
155
|
+
const out = {};
|
|
156
|
+
for (const line of raw.split("\n")) {
|
|
157
|
+
const trimmed = line.trim();
|
|
158
|
+
if (trimmed === "" || trimmed.startsWith("#"))
|
|
159
|
+
continue;
|
|
160
|
+
const colon = trimmed.indexOf(":");
|
|
161
|
+
if (colon === -1)
|
|
162
|
+
continue;
|
|
163
|
+
out[trimmed.slice(0, colon).trim()] = trimmed.slice(colon + 1).trim();
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
121
167
|
|
|
122
168
|
// ../../dist/core/ledger.js
|
|
123
169
|
var import_node_fs3 = require("node:fs");
|
|
@@ -130,6 +176,11 @@ function appendLedger(path, record) {
|
|
|
130
176
|
atomicWrite(path, existing + `${JSON.stringify(record)}
|
|
131
177
|
`);
|
|
132
178
|
}
|
|
179
|
+
function readLedger(path) {
|
|
180
|
+
if (!(0, import_node_fs3.existsSync)(path))
|
|
181
|
+
return [];
|
|
182
|
+
return (0, import_node_fs3.readFileSync)(path, "utf8").split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line));
|
|
183
|
+
}
|
|
133
184
|
function readSequences(root) {
|
|
134
185
|
const path = (0, import_node_path3.join)(root, SEQUENCES_FILE);
|
|
135
186
|
if (!(0, import_node_fs3.existsSync)(path))
|
|
@@ -490,6 +541,132 @@ function listEntries(root, options) {
|
|
|
490
541
|
}
|
|
491
542
|
return out;
|
|
492
543
|
}
|
|
544
|
+
function findTitleConflict(root, title, excludeId) {
|
|
545
|
+
const hit = listEntries(root).find((entry) => entry.frontmatter.title === title && entry.frontmatter.id !== excludeId);
|
|
546
|
+
return hit ?? null;
|
|
547
|
+
}
|
|
548
|
+
function commitKnowledge(root, input, helpers) {
|
|
549
|
+
const ts = helpers.nowIsoValue ?? nowIso();
|
|
550
|
+
if (input.id === void 0) {
|
|
551
|
+
const conflict = findTitleConflict(root, input.title);
|
|
552
|
+
if (conflict !== null) {
|
|
553
|
+
throw new HubError(ErrorCode.E_CONFLICT, `an accepted entry with the same title exists: ${conflict.frontmatter.id}`, {
|
|
554
|
+
existingId: conflict.frontmatter.id,
|
|
555
|
+
existingTitle: conflict.frontmatter.title
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
const id = nextKnowledgeId(root, input.type, helpers.readSequences, helpers.writeSequences);
|
|
559
|
+
const fm2 = {
|
|
560
|
+
id,
|
|
561
|
+
version: 1,
|
|
562
|
+
type: input.type,
|
|
563
|
+
status: "accepted",
|
|
564
|
+
title: input.title,
|
|
565
|
+
summary: input.summary,
|
|
566
|
+
scope: input.scope,
|
|
567
|
+
tags: input.tags ?? [],
|
|
568
|
+
created: ts,
|
|
569
|
+
updated: ts,
|
|
570
|
+
last_verified: ts,
|
|
571
|
+
extra: input.expiresAt !== void 0 ? { expires_at: input.expiresAt } : {}
|
|
572
|
+
};
|
|
573
|
+
const path = entryPath(root, input.type, id);
|
|
574
|
+
atomicWrite(path, renderKnowledgeMarkdown(fm2, input.body));
|
|
575
|
+
helpers.appendLedger(root, {
|
|
576
|
+
ts,
|
|
577
|
+
actor: input.actor ?? "human",
|
|
578
|
+
action: "approve",
|
|
579
|
+
id,
|
|
580
|
+
version: 1,
|
|
581
|
+
source_refs: input.sourceRefs
|
|
582
|
+
});
|
|
583
|
+
return { id, version: 1, path };
|
|
584
|
+
}
|
|
585
|
+
let previous;
|
|
586
|
+
try {
|
|
587
|
+
const found = getEntry(root, input.id);
|
|
588
|
+
previous = { frontmatter: found.frontmatter, path: found.path, body: found.body };
|
|
589
|
+
} catch {
|
|
590
|
+
const fm2 = {
|
|
591
|
+
id: input.id,
|
|
592
|
+
version: 1,
|
|
593
|
+
type: input.type,
|
|
594
|
+
status: "accepted",
|
|
595
|
+
title: input.title,
|
|
596
|
+
summary: input.summary,
|
|
597
|
+
scope: input.scope,
|
|
598
|
+
tags: input.tags ?? [],
|
|
599
|
+
created: ts,
|
|
600
|
+
updated: ts,
|
|
601
|
+
last_verified: ts,
|
|
602
|
+
extra: input.expiresAt !== void 0 ? { expires_at: input.expiresAt } : {}
|
|
603
|
+
};
|
|
604
|
+
const path = entryPath(root, input.type, input.id);
|
|
605
|
+
atomicWrite(path, renderKnowledgeMarkdown(fm2, input.body));
|
|
606
|
+
helpers.appendLedger(root, {
|
|
607
|
+
ts,
|
|
608
|
+
actor: input.actor ?? "human",
|
|
609
|
+
action: "approve",
|
|
610
|
+
id: input.id,
|
|
611
|
+
version: 1,
|
|
612
|
+
source_refs: input.sourceRefs
|
|
613
|
+
});
|
|
614
|
+
return { id: input.id, version: 1, path };
|
|
615
|
+
}
|
|
616
|
+
const prevFm = previous.frontmatter;
|
|
617
|
+
if (prevFm.type !== input.type) {
|
|
618
|
+
throw new HubError(ErrorCode.E_VALIDATION, `type mismatch for ${input.id}: ${prevFm.type} \u2260 ${input.type}`);
|
|
619
|
+
}
|
|
620
|
+
const historyPath = (0, import_node_path4.join)(historyDir(root, prevFm.type), `${prevFm.id}@v${prevFm.version}.md`);
|
|
621
|
+
atomicWrite(historyPath, (0, import_node_fs4.readFileSync)(previous.path, "utf8"));
|
|
622
|
+
const fm = {
|
|
623
|
+
...prevFm,
|
|
624
|
+
version: prevFm.version + 1,
|
|
625
|
+
title: input.title,
|
|
626
|
+
summary: input.summary,
|
|
627
|
+
tags: input.tags ?? prevFm.tags,
|
|
628
|
+
updated: ts,
|
|
629
|
+
last_verified: ts,
|
|
630
|
+
extra: input.expiresAt !== void 0 ? { ...prevFm.extra, expires_at: input.expiresAt } : prevFm.extra
|
|
631
|
+
};
|
|
632
|
+
atomicWrite(previous.path, renderKnowledgeMarkdown(fm, input.body));
|
|
633
|
+
helpers.appendLedger(root, {
|
|
634
|
+
ts,
|
|
635
|
+
actor: input.actor ?? "human",
|
|
636
|
+
action: "update",
|
|
637
|
+
id: prevFm.id,
|
|
638
|
+
version: fm.version,
|
|
639
|
+
source_refs: input.sourceRefs
|
|
640
|
+
});
|
|
641
|
+
return { id: prevFm.id, version: fm.version, path: previous.path };
|
|
642
|
+
}
|
|
643
|
+
function deprecateEntry(root, id, reason, helpers) {
|
|
644
|
+
const entry = getEntry(root, id);
|
|
645
|
+
const ts = helpers.nowIsoValue ?? nowIso();
|
|
646
|
+
const fm = { ...entry.frontmatter, status: "deprecated", updated: ts };
|
|
647
|
+
atomicWrite(entry.path, renderKnowledgeMarkdown(fm, entry.body));
|
|
648
|
+
helpers.appendLedger(root, {
|
|
649
|
+
ts,
|
|
650
|
+
actor: "human",
|
|
651
|
+
action: "deprecate",
|
|
652
|
+
id,
|
|
653
|
+
version: entry.frontmatter.version,
|
|
654
|
+
note: reason
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
function hardDeleteEntry(root, id, reason, helpers) {
|
|
658
|
+
const entry = getEntry(root, id);
|
|
659
|
+
const ts = helpers.nowIsoValue ?? nowIso();
|
|
660
|
+
helpers.appendLedger(root, {
|
|
661
|
+
ts,
|
|
662
|
+
actor: "human",
|
|
663
|
+
action: "delete",
|
|
664
|
+
id,
|
|
665
|
+
version: entry.frontmatter.version,
|
|
666
|
+
note: reason
|
|
667
|
+
});
|
|
668
|
+
(0, import_node_fs4.rmSync)(entry.path, { force: true });
|
|
669
|
+
}
|
|
493
670
|
function createProposal(root, input, helpers) {
|
|
494
671
|
const ts = helpers.nowIsoValue ?? nowIso();
|
|
495
672
|
const proposalId = nextProposalId(root, helpers.readSequences, helpers.writeSequences);
|
|
@@ -579,6 +756,19 @@ function resolveWorkspace(dir, explicitId) {
|
|
|
579
756
|
const canonical = root ?? abs;
|
|
580
757
|
return { workspaceId: slugifyDir(canonical), name: (0, import_node_path5.basename)(canonical), path: canonical, exact: true };
|
|
581
758
|
}
|
|
759
|
+
function registerWorkspace(hubRoot, ws, nowIso2, readConfig, writeConfig) {
|
|
760
|
+
const config = readConfig(hubRoot);
|
|
761
|
+
const nameKey = `workspaces.${ws.workspaceId}.name`;
|
|
762
|
+
if (config[nameKey] !== void 0) {
|
|
763
|
+
return;
|
|
764
|
+
}
|
|
765
|
+
const lines = [`workspaces.${ws.workspaceId}.name: ${ws.name}`];
|
|
766
|
+
if (ws.origin !== void 0)
|
|
767
|
+
lines.push(`workspaces.${ws.workspaceId}.origin: ${ws.origin}`);
|
|
768
|
+
lines.push(`workspaces.${ws.workspaceId}.registeredAt: ${nowIso2()}`);
|
|
769
|
+
writeConfig(hubRoot, `${lines.join("\n")}
|
|
770
|
+
`);
|
|
771
|
+
}
|
|
582
772
|
|
|
583
773
|
// ../../dist/core/lock.js
|
|
584
774
|
var import_node_fs5 = require("node:fs");
|
|
@@ -871,12 +1061,36 @@ function preflightIndex(hubRoot, nowIso2) {
|
|
|
871
1061
|
return buildIndex(hubRoot, nowIso2 ?? (() => (/* @__PURE__ */ new Date()).toISOString()));
|
|
872
1062
|
}
|
|
873
1063
|
|
|
874
|
-
// ../../dist/core/
|
|
1064
|
+
// ../../dist/core/journal.js
|
|
875
1065
|
var import_node_fs6 = require("node:fs");
|
|
876
1066
|
var import_node_path7 = require("node:path");
|
|
1067
|
+
function readJournal(root, day) {
|
|
1068
|
+
const dir = journalDir(root);
|
|
1069
|
+
if (!(0, import_node_fs6.existsSync)(dir))
|
|
1070
|
+
return [];
|
|
1071
|
+
const files = day !== void 0 ? [(0, import_node_path7.join)(dir, `${day}.jsonl`)] : (0, import_node_fs6.readdirSync)(dir).filter((f) => f.endsWith(".jsonl")).sort().map((f) => (0, import_node_path7.join)(dir, f));
|
|
1072
|
+
const out = [];
|
|
1073
|
+
for (const file of files) {
|
|
1074
|
+
if (!(0, import_node_fs6.existsSync)(file))
|
|
1075
|
+
continue;
|
|
1076
|
+
for (const line of (0, import_node_fs6.readFileSync)(file, "utf8").split("\n")) {
|
|
1077
|
+
if (line.trim() === "")
|
|
1078
|
+
continue;
|
|
1079
|
+
try {
|
|
1080
|
+
out.push(JSON.parse(line));
|
|
1081
|
+
} catch {
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
return out;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// ../../dist/core/transcript.js
|
|
1089
|
+
var import_node_fs7 = require("node:fs");
|
|
1090
|
+
var import_node_path8 = require("node:path");
|
|
877
1091
|
var TRANSCRIPT_INDEX_FILE = "records/transcript-index.jsonl";
|
|
878
1092
|
function indexPath(root) {
|
|
879
|
-
return (0,
|
|
1093
|
+
return (0, import_node_path8.join)(root, TRANSCRIPT_INDEX_FILE);
|
|
880
1094
|
}
|
|
881
1095
|
function indexTranscript(root, input) {
|
|
882
1096
|
const tokens = [...new Set(tokenize(input.text))];
|
|
@@ -887,16 +1101,16 @@ function indexTranscript(root, input) {
|
|
|
887
1101
|
preview: input.text.replace(/\s+/g, " ").slice(0, 160),
|
|
888
1102
|
location: input.location
|
|
889
1103
|
};
|
|
890
|
-
(0,
|
|
1104
|
+
(0, import_node_fs7.appendFileSync)(indexPath(root), `${JSON.stringify(record)}
|
|
891
1105
|
`, "utf8");
|
|
892
1106
|
return record;
|
|
893
1107
|
}
|
|
894
1108
|
function readTranscriptIndex(root) {
|
|
895
1109
|
const path = indexPath(root);
|
|
896
|
-
if (!(0,
|
|
1110
|
+
if (!(0, import_node_fs7.existsSync)(path))
|
|
897
1111
|
return [];
|
|
898
1112
|
const out = [];
|
|
899
|
-
for (const line of (0,
|
|
1113
|
+
for (const line of (0, import_node_fs7.readFileSync)(path, "utf8").split("\n")) {
|
|
900
1114
|
if (line.trim() === "")
|
|
901
1115
|
continue;
|
|
902
1116
|
try {
|
|
@@ -932,6 +1146,586 @@ function detectDejaVu(root, query, threshold) {
|
|
|
932
1146
|
return hits.sort((a, b) => b.overlap - a.overlap);
|
|
933
1147
|
}
|
|
934
1148
|
|
|
1149
|
+
// ../../dist/transport/http.js
|
|
1150
|
+
var import_node_http = require("node:http");
|
|
1151
|
+
|
|
1152
|
+
// ../../dist/transport/panel.js
|
|
1153
|
+
var PANEL_HTML = `<!doctype html>
|
|
1154
|
+
<html lang="zh">
|
|
1155
|
+
<head>
|
|
1156
|
+
<meta charset="utf-8">
|
|
1157
|
+
<title>memhub console</title>
|
|
1158
|
+
<style>
|
|
1159
|
+
:root { color-scheme: dark; }
|
|
1160
|
+
body { font-family: ui-sans-serif, system-ui; margin: 0; background: #0f1115; color: #e6e6e6; }
|
|
1161
|
+
header { padding: 14px 20px; border-bottom: 1px solid #262b36; display: flex; gap: 16px; align-items: baseline; }
|
|
1162
|
+
header h1 { font-size: 16px; margin: 0; }
|
|
1163
|
+
header span { color: #8b93a7; font-size: 12px; }
|
|
1164
|
+
nav { display: flex; gap: 4px; padding: 0 20px; border-bottom: 1px solid #262b36; }
|
|
1165
|
+
nav button { border: none; background: none; color: #8b93a7; padding: 10px 16px; font-size: 14px; cursor: pointer; border-bottom: 2px solid transparent; }
|
|
1166
|
+
nav button.active { color: #e6e6e6; border-bottom-color: #4d7cff; }
|
|
1167
|
+
main { max-width: 900px; margin: 0 auto; padding: 16px; }
|
|
1168
|
+
.card { border: 1px solid #262b36; border-radius: 10px; padding: 14px 16px; margin: 10px 0; background: #161a22; }
|
|
1169
|
+
.card h3 { margin: 0 0 6px; font-size: 14px; }
|
|
1170
|
+
.meta { color: #8b93a7; font-size: 12px; margin-bottom: 8px; }
|
|
1171
|
+
.grade { border-radius: 6px; padding: 1px 8px; font-size: 11px; }
|
|
1172
|
+
.grade.individual { background: #3a2a2a; color: #ff9e9e; }
|
|
1173
|
+
.grade.batch { background: #233a2c; color: #8ee39b; }
|
|
1174
|
+
.status-tag { border-radius: 6px; padding: 1px 8px; font-size: 11px; background: #262b36; color: #a9b1c2; }
|
|
1175
|
+
.status-tag.deprecated { background: #3a2f1e; color: #e3b98e; }
|
|
1176
|
+
button { border: 1px solid #2f3542; background: #1d2330; color: #e6e6e6; border-radius: 8px; padding: 6px 14px; cursor: pointer; font-size: 13px; }
|
|
1177
|
+
button:hover { background: #262d3d; }
|
|
1178
|
+
button.primary { background: #245639; border-color: #2f7a4d; }
|
|
1179
|
+
button.danger { background: #5a2a2a; border-color: #7a3a3a; }
|
|
1180
|
+
.row { display: flex; gap: 8px; margin-top: 8px; }
|
|
1181
|
+
#statusbar { font-size: 12px; color: #8b93a7; }
|
|
1182
|
+
pre { white-space: pre-wrap; font-size: 12px; color: #a9b1c2; }
|
|
1183
|
+
.empty { color: #8b93a7; padding: 30px 0; text-align: center; }
|
|
1184
|
+
#batchbar { display: none; margin: 10px 0; }
|
|
1185
|
+
.tabpane { display: none; }
|
|
1186
|
+
.tabpane.active { display: block; }
|
|
1187
|
+
.entryline { border-bottom: 1px solid #20242e; padding: 9px 4px; cursor: pointer; display: flex; gap: 10px; align-items: baseline; }
|
|
1188
|
+
.entryline:hover { background: #1a1f29; }
|
|
1189
|
+
.entryline .id { color: #6f9bff; font-size: 12px; min-width: 90px; }
|
|
1190
|
+
.entryline .title { flex: 1; font-size: 13px; }
|
|
1191
|
+
.entryline .type { color: #8b93a7; font-size: 11px; }
|
|
1192
|
+
.detail pre { background: #12151c; border-radius: 8px; padding: 12px; max-height: 320px; overflow: auto; }
|
|
1193
|
+
</style>
|
|
1194
|
+
</head>
|
|
1195
|
+
<body>
|
|
1196
|
+
<header><h1>memhub console</h1><span id="statusbar">loading\u2026</span></header>
|
|
1197
|
+
<nav>
|
|
1198
|
+
<button id="tab-inbox" class="active" onclick="showTab('inbox')">\u6536\u4EF6\u7BB1</button>
|
|
1199
|
+
<button id="tab-entries" onclick="showTab('entries')">\u8BB0\u5FC6\u5E93</button>
|
|
1200
|
+
<button id="tab-audit" onclick="showTab('audit')">\u5BA1\u8BA1</button>
|
|
1201
|
+
</nav>
|
|
1202
|
+
<main>
|
|
1203
|
+
<div id="pane-inbox" class="tabpane active">
|
|
1204
|
+
<div id="batchbar"><button class="primary" onclick="approveBatch()">\u6279\u51C6\u6240\u9009\u4F4E\u98CE\u9669\u6761\u76EE\uFF08\u6279\u91CF\uFF09</button></div>
|
|
1205
|
+
<div id="inbox"><div class="empty">\u52A0\u8F7D\u4E2D\u2026</div></div>
|
|
1206
|
+
</div>
|
|
1207
|
+
<div id="pane-entries" class="tabpane">
|
|
1208
|
+
<div class="row"><input id="q" placeholder="BM25 \u68C0\u7D22\u2026" style="flex:1" onkeydown="if(event.key==='Enter')doSearch()"><button onclick="doSearch()">\u641C\u7D22</button><button onclick="loadEntries()">\u5168\u90E8</button></div>
|
|
1209
|
+
<div id="entrylist"><div class="empty">\u70B9\u51FB\u300C\u5168\u90E8\u300D\u6D4F\u89C8\u6216\u8F93\u5165\u68C0\u7D22\u8BCD</div></div>
|
|
1210
|
+
<div id="entrydetail" class="detail"></div>
|
|
1211
|
+
</div>
|
|
1212
|
+
<div id="pane-audit" class="tabpane">
|
|
1213
|
+
<div class="row"><button onclick="loadLedger()">\u5237\u65B0\u8D26\u672C</button><button onclick="loadJournal()">\u5237\u65B0\u60C5\u666F\u65E5\u5FD7</button></div>
|
|
1214
|
+
<div id="auditview"><div class="empty">\u70B9\u51FB\u5237\u65B0\u52A0\u8F7D</div></div>
|
|
1215
|
+
</div>
|
|
1216
|
+
</main>
|
|
1217
|
+
<script>
|
|
1218
|
+
let inbox = [];
|
|
1219
|
+
async function j(url, opts) { const r = await fetch(url, opts); return { ok: r.ok, status: r.status, data: await r.json().catch(() => ({})) }; }
|
|
1220
|
+
function esc(s) { return String(s ?? '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
|
1221
|
+
function showTab(name) {
|
|
1222
|
+
document.querySelectorAll('.tabpane').forEach(p => p.classList.remove('active'));
|
|
1223
|
+
document.getElementById('pane-' + name).classList.add('active');
|
|
1224
|
+
document.querySelectorAll('nav button').forEach(b => b.classList.remove('active'));
|
|
1225
|
+
document.getElementById('tab-' + name).classList.add('active');
|
|
1226
|
+
if (name === 'inbox') refreshInbox();
|
|
1227
|
+
if (name === 'entries' && document.getElementById('entrylist').dataset.loaded !== '1') loadEntries();
|
|
1228
|
+
}
|
|
1229
|
+
async function refreshStatus() {
|
|
1230
|
+
const s = await j('/api/status');
|
|
1231
|
+
document.getElementById('statusbar').textContent =
|
|
1232
|
+
(s.data.workspace ? s.data.workspace.workspaceId + (s.data.workspace.exact ? '' : ' (synthetic)') : '?') +
|
|
1233
|
+
' \xB7 accepted ' + (s.data.acceptedCount ?? 0) + ' \xB7 hub ' + (s.data.hubRoot ?? '?');
|
|
1234
|
+
}
|
|
1235
|
+
async function refreshInbox() {
|
|
1236
|
+
refreshStatus();
|
|
1237
|
+
const i = await j('/api/inbox');
|
|
1238
|
+
inbox = i.data.proposals ?? [];
|
|
1239
|
+
const el = document.getElementById('inbox');
|
|
1240
|
+
if (inbox.length === 0) { el.innerHTML = '<div class="empty">\u2713 inbox \u6E05\u7A7A\uFF0C\u65E0\u5F85\u5BA1\u6761\u76EE</div>'; }
|
|
1241
|
+
else {
|
|
1242
|
+
el.innerHTML = inbox.map(p => \`
|
|
1243
|
+
<div class="card" id="card-\${p.id}">
|
|
1244
|
+
<h3>\${esc(p.title)} <span class="grade \${p.grade}">\${p.grade === 'individual' ? '\u9010\u6761\u5BA1\u6279' : '\u53EF\u6279\u91CF'}</span></h3>
|
|
1245
|
+
<div class="meta">\${esc(p.id)} \xB7 \${esc(p.type)} \xB7 \${esc((p.tags ?? []).join(', '))}</div>
|
|
1246
|
+
<div>\${esc(p.summary)}</div>
|
|
1247
|
+
<div class="row">
|
|
1248
|
+
<button class="primary" onclick="approveOne('\${p.id}')">\u6279\u51C6</button>
|
|
1249
|
+
<button class="danger" onclick="rejectOne('\${p.id}')">\u62D2\u7EDD</button>
|
|
1250
|
+
</div>
|
|
1251
|
+
</div>\`).join('');
|
|
1252
|
+
}
|
|
1253
|
+
const batchables = inbox.filter(p => p.grade === 'batch');
|
|
1254
|
+
document.getElementById('batchbar').style.display = batchables.length > 1 ? 'block' : 'none';
|
|
1255
|
+
}
|
|
1256
|
+
async function approveOne(id) { await j('/api/inbox/' + id + '/approve', { method: 'POST', headers: {'content-type':'application/json'}, body: '{}' }); refreshInbox(); }
|
|
1257
|
+
async function rejectOne(id) { await j('/api/inbox/' + id + '/reject', { method: 'POST', headers: {'content-type':'application/json'}, body: '{}' }); refreshInbox(); }
|
|
1258
|
+
async function approveBatch() {
|
|
1259
|
+
const ids = inbox.filter(p => p.grade === 'batch').map(p => p.id);
|
|
1260
|
+
await j('/api/inbox/approve', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ ids }) });
|
|
1261
|
+
refreshInbox();
|
|
1262
|
+
}
|
|
1263
|
+
async function loadEntries() {
|
|
1264
|
+
const r = await j('/api/entries');
|
|
1265
|
+
renderEntries(r.data.entries ?? []);
|
|
1266
|
+
document.getElementById('entrylist').dataset.loaded = '1';
|
|
1267
|
+
}
|
|
1268
|
+
async function doSearch() {
|
|
1269
|
+
const q = document.getElementById('q').value;
|
|
1270
|
+
if (q === '') return loadEntries();
|
|
1271
|
+
const r = await j('/api/search', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ query: q, limit: 25 }) });
|
|
1272
|
+
renderEntries((r.data.hits ?? []).map(h => ({ id: h.id, type: h.type, status: 'accepted', title: h.title, summary: h.abstract, score: h.score })));
|
|
1273
|
+
}
|
|
1274
|
+
function renderEntries(entries) {
|
|
1275
|
+
const el = document.getElementById('entrylist');
|
|
1276
|
+
if (entries.length === 0) { el.innerHTML = '<div class="empty">\u65E0\u6761\u76EE</div>'; return; }
|
|
1277
|
+
el.innerHTML = entries.map(e => \`
|
|
1278
|
+
<div class="entryline" onclick="openEntry('\${esc(e.id)}')">
|
|
1279
|
+
<span class="id">\${esc(e.id)}@v\${e.version ?? '?'}</span>
|
|
1280
|
+
<span class="title">\${esc(e.title)} <span class="status-tag \${e.status === 'deprecated' ? 'deprecated' : ''}">\${esc(e.status ?? '')}</span>\${e.score !== undefined ? ' \xB7 ' + Number(e.score).toFixed(2) : ''}</span>
|
|
1281
|
+
<span class="type">\${esc(e.type)}</span>
|
|
1282
|
+
</div>\`).join('');
|
|
1283
|
+
}
|
|
1284
|
+
async function openEntry(id) {
|
|
1285
|
+
const r = await j('/api/entries/' + id);
|
|
1286
|
+
if (!r.ok) { document.getElementById('entrydetail').innerHTML = '<div class="card">\u52A0\u8F7D\u5931\u8D25: ' + esc(r.data.error ?? r.status) + '</div>'; return; }
|
|
1287
|
+
const fm = r.data.frontmatter ?? {};
|
|
1288
|
+
document.getElementById('entrydetail').innerHTML = \`
|
|
1289
|
+
<div class="card">
|
|
1290
|
+
<h3>\${esc(fm.title)} <span class="status-tag">\${esc(fm.status)}</span></h3>
|
|
1291
|
+
<div class="meta">\${esc(fm.id)}@v\${fm.version} \xB7 \${esc(fm.type)} \xB7 \${esc(JSON.stringify(fm.scope))} \xB7 \${esc((fm.tags ?? []).join(', '))}</div>
|
|
1292
|
+
<div class="meta">path: \${esc(r.data.path)}</div>
|
|
1293
|
+
<pre id="entry-body">\${esc(r.data.body)}</pre>
|
|
1294
|
+
<div class="row">
|
|
1295
|
+
<button class="primary" onclick="editEntry('\${esc(id)}')">\u7F16\u8F91\uFF08\u91CD\u65B0\u8403\u53D6\uFF09</button>
|
|
1296
|
+
<button class="danger" onclick="deprecateEntry('\${esc(id)}')">\u5E9F\u5F03\uFF08\u8F6F\u5220\u9664\uFF09</button>
|
|
1297
|
+
<button class="danger" onclick="hardDeleteEntry('\${esc(id)}')">\u6C38\u4E45\u5220\u9664\uFF08\u4E0D\u53EF\u6062\u590D\uFF09</button>
|
|
1298
|
+
</div>
|
|
1299
|
+
</div>\`;
|
|
1300
|
+
}
|
|
1301
|
+
async function editEntry(id) {
|
|
1302
|
+
const r = await j('/api/entries/' + id);
|
|
1303
|
+
if (!r.ok) { alert('\u52A0\u8F7D\u5931\u8D25: ' + (r.data.error ?? r.status)); return; }
|
|
1304
|
+
const fm = r.data.frontmatter ?? {};
|
|
1305
|
+
document.getElementById('entrydetail').innerHTML = \`
|
|
1306
|
+
<div class="card">
|
|
1307
|
+
<h3>\u7F16\u8F91 \${esc(fm.id)}\uFF08\u4FDD\u5B58 = v\${(fm.version ?? 1) + 1}\uFF0C\u65E7\u7248\u672C\u8FDB history/\uFF09</h3>
|
|
1308
|
+
<div class="meta">\u6807\u9898\u4E0E\u7C7B\u578B\u4E0D\u53EF\u6539\uFF1B\u6458\u8981\u4E0E\u6B63\u6587\u901A\u7528\u5316\u6539\u5199\u540E\u4FDD\u5B58\u5373\u91CD\u65B0\u8403\u53D6\u3002</div>
|
|
1309
|
+
<div style="margin:8px 0"><label>\u6458\u8981</label><br><textarea id="edit-summary" rows="3" style="width:98%">\${esc(fm.summary)}</textarea></div>
|
|
1310
|
+
<div style="margin:8px 0"><label>\u6B63\u6587</label><br><textarea id="edit-body" rows="14" style="width:98%;font-family:monospace">\${esc(r.data.body)}</textarea></div>
|
|
1311
|
+
<div class="row">
|
|
1312
|
+
<button class="primary" onclick="saveEntry('\${esc(id)}')">\u4FDD\u5B58\u4E3A\u65B0\u7248\u672C</button>
|
|
1313
|
+
<button onclick="openEntry('\${esc(id)}')">\u53D6\u6D88</button>
|
|
1314
|
+
</div>
|
|
1315
|
+
</div>\`;
|
|
1316
|
+
}
|
|
1317
|
+
async function saveEntry(id) {
|
|
1318
|
+
const payload = { summary: document.getElementById('edit-summary').value, body: document.getElementById('edit-body').value };
|
|
1319
|
+
const r = await j('/api/entries/' + id + '/update', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify(payload) });
|
|
1320
|
+
if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class="card">\u2713 \u5DF2\u4FDD\u5B58 ' + esc(r.data.updated) + '@v' + esc(r.data.version) + '\uFF08\u65E7\u7248\u672C\u8FDB history/\uFF0C\u8D26\u672C\u5DF2\u8BB0\u5F55\uFF09</div>'; loadEntries(); }
|
|
1321
|
+
else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));
|
|
1322
|
+
}
|
|
1323
|
+
async function deprecateEntry(id) {
|
|
1324
|
+
if (!confirm('\u786E\u8BA4\u5E9F\u5F03 ' + id + '\uFF1F\uFF08status=deprecated\uFF0C\u53EF\u8FFD\u6EAF\uFF09')) return;
|
|
1325
|
+
const reason = prompt('\u5E9F\u5F03\u539F\u56E0\uFF1A', 'via console') ?? '';
|
|
1326
|
+
const r = await j('/api/entries/' + id + '/deprecate', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ reason }) });
|
|
1327
|
+
if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class="card">\u2713 \u5DF2\u5E9F\u5F03 ' + esc(id) + '</div>'; loadEntries(); }
|
|
1328
|
+
else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));
|
|
1329
|
+
}
|
|
1330
|
+
async function hardDeleteEntry(id) {
|
|
1331
|
+
if (!confirm('\u6C38\u4E45\u5220\u9664 ' + id + '\uFF1F\u6587\u4EF6\u5C06\u88AB\u7269\u7406\u5220\u9664\uFF0C\u4E0D\u53EF\u6062\u590D\uFF08\u8D26\u672C\u7559\u75D5\uFF09\u3002')) return;
|
|
1332
|
+
if (!confirm('\u518D\u6B21\u786E\u8BA4\uFF1A\u771F\u7684\u8981\u6C38\u4E45\u5220\u9664 ' + id + ' \u5417\uFF1F')) return;
|
|
1333
|
+
const reason = prompt('\u5220\u9664\u539F\u56E0\uFF1A', 'via console') ?? '';
|
|
1334
|
+
const r = await j('/api/entries/' + id + '/delete', { method: 'POST', headers: {'content-type':'application/json'}, body: JSON.stringify({ reason }) });
|
|
1335
|
+
if (r.ok) { document.getElementById('entrydetail').innerHTML = '<div class="card">\u2713 \u5DF2\u6C38\u4E45\u5220\u9664 ' + esc(id) + '\uFF08\u8D26\u672C\u7559\u75D5\uFF09</div>'; loadEntries(); }
|
|
1336
|
+
else alert('\u5931\u8D25: ' + (r.data.error ?? r.status));
|
|
1337
|
+
}
|
|
1338
|
+
async function loadLedger() {
|
|
1339
|
+
const r = await j('/api/ledger');
|
|
1340
|
+
const records = r.data.records ?? [];
|
|
1341
|
+
document.getElementById('auditview').innerHTML = '<div class="card"><h3>\u8D26\u672C\u4E8B\u4EF6\uFF08\u6700\u8FD1 ' + records.length + ' / \u5171 ' + (r.data.total ?? 0) + '\uFF09</h3><pre>' + esc(JSON.stringify(records, null, 2)) + '</pre></div>';
|
|
1342
|
+
}
|
|
1343
|
+
async function loadJournal() {
|
|
1344
|
+
const r = await j('/api/journal');
|
|
1345
|
+
const entries = r.data.entries ?? [];
|
|
1346
|
+
document.getElementById('auditview').innerHTML = '<div class="card"><h3>\u60C5\u666F\u65E5\u5FD7\uFF08\u6700\u8FD1 ' + entries.length + '\uFF09</h3><pre>' + esc(JSON.stringify(entries, null, 2)) + '</pre></div>';
|
|
1347
|
+
}
|
|
1348
|
+
refreshInbox();
|
|
1349
|
+
</script>
|
|
1350
|
+
</body>
|
|
1351
|
+
</html>`;
|
|
1352
|
+
|
|
1353
|
+
// ../../dist/transport/server.js
|
|
1354
|
+
var import_node_fs8 = require("node:fs");
|
|
1355
|
+
var import_node_path9 = require("node:path");
|
|
1356
|
+
|
|
1357
|
+
// ../../dist/transport/autocommit.js
|
|
1358
|
+
var import_node_child_process2 = require("node:child_process");
|
|
1359
|
+
function autoCommit(root, message) {
|
|
1360
|
+
const inside = (0, import_node_child_process2.spawnSync)("git", ["rev-parse", "--is-inside-work-tree"], { cwd: root, encoding: "utf8" });
|
|
1361
|
+
if (inside.error !== void 0 || inside.status !== 0)
|
|
1362
|
+
return { committed: false, detail: "not a git repository" };
|
|
1363
|
+
const add = (0, import_node_child_process2.spawnSync)("git", ["add", "-A"], { cwd: root, encoding: "utf8" });
|
|
1364
|
+
if (add.error !== void 0 || add.status !== 0)
|
|
1365
|
+
return { committed: false, detail: `git add failed: ${(add.stderr ?? "").trim().slice(0, 200)}` };
|
|
1366
|
+
const commit = (0, import_node_child_process2.spawnSync)("git", ["commit", "-m", message], { cwd: root, encoding: "utf8" });
|
|
1367
|
+
const output = `${commit.stdout ?? ""}${commit.stderr ?? ""}`;
|
|
1368
|
+
if (commit.status !== 0) {
|
|
1369
|
+
if (output.includes("nothing to commit"))
|
|
1370
|
+
return { committed: false, detail: "nothing to commit" };
|
|
1371
|
+
return { committed: false, detail: output.trim().slice(0, 200) };
|
|
1372
|
+
}
|
|
1373
|
+
return { committed: true };
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
// ../../dist/transport/server.js
|
|
1377
|
+
var INDIVIDUAL_TYPES = ["decision", "constraint", "api-catalog"];
|
|
1378
|
+
function gradeFor(type) {
|
|
1379
|
+
return INDIVIDUAL_TYPES.includes(type) ? "individual" : "batch";
|
|
1380
|
+
}
|
|
1381
|
+
function createApiState(hubRoot, workspaceArg) {
|
|
1382
|
+
const workspace = resolveWorkspace(process.cwd(), workspaceArg);
|
|
1383
|
+
const index = buildIndex(hubRoot, () => (/* @__PURE__ */ new Date()).toISOString());
|
|
1384
|
+
return { hubRoot, workspace, index, metrics: emptyMetrics(index) };
|
|
1385
|
+
}
|
|
1386
|
+
function ok(body) {
|
|
1387
|
+
return { status: 200, body };
|
|
1388
|
+
}
|
|
1389
|
+
function bad(status, message, details) {
|
|
1390
|
+
return { status, body: { error: message, details } };
|
|
1391
|
+
}
|
|
1392
|
+
function withWriteLock(hubRoot, fn) {
|
|
1393
|
+
const acquired = acquireLock(hubRoot);
|
|
1394
|
+
if (!acquired.ok) {
|
|
1395
|
+
throw new HubError(ErrorCode.E_READONLY, "another writer holds the lease", { holder: acquired.holder });
|
|
1396
|
+
}
|
|
1397
|
+
const token = acquired.lock?.token ?? "";
|
|
1398
|
+
try {
|
|
1399
|
+
assertFencing(hubRoot, token);
|
|
1400
|
+
return fn();
|
|
1401
|
+
} finally {
|
|
1402
|
+
releaseLock(hubRoot, token);
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
function commitOne(hubRoot, proposalId, note) {
|
|
1406
|
+
const proposal = listProposals(hubRoot).find((p) => p.id === proposalId);
|
|
1407
|
+
if (proposal === void 0) {
|
|
1408
|
+
throw new HubError(ErrorCode.E_NOT_FOUND, `pending proposal not found: ${proposalId}`, { proposalId });
|
|
1409
|
+
}
|
|
1410
|
+
const rawOriginId = proposal.frontmatter.extra["origin_id"];
|
|
1411
|
+
const originId = typeof rawOriginId === "string" && rawOriginId !== "" && rawOriginId !== "[]" ? rawOriginId : void 0;
|
|
1412
|
+
const rawSupersedes = proposal.frontmatter.extra["supersedes"];
|
|
1413
|
+
const supersedesTarget = typeof rawSupersedes === "string" && rawSupersedes !== "" && rawSupersedes !== "[]" ? rawSupersedes.split(/\s+/)[0] : void 0;
|
|
1414
|
+
const targetId = originId ?? supersedesTarget;
|
|
1415
|
+
const superseding = targetId !== void 0 && (originId !== void 0 || existsSyncSafe(hubRoot, targetId));
|
|
1416
|
+
const committed = commitKnowledge(hubRoot, {
|
|
1417
|
+
...superseding ? { id: targetId } : {},
|
|
1418
|
+
type: proposal.frontmatter.type,
|
|
1419
|
+
title: proposal.frontmatter.title,
|
|
1420
|
+
summary: proposal.frontmatter.summary,
|
|
1421
|
+
scope: proposal.frontmatter.scope,
|
|
1422
|
+
tags: proposal.frontmatter.tags,
|
|
1423
|
+
body: (0, import_node_fs8.readFileSync)(proposal.path, "utf8").split("---")[2]?.trim() ?? "",
|
|
1424
|
+
actor: "panel"
|
|
1425
|
+
}, { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) });
|
|
1426
|
+
(0, import_node_fs8.unlinkSync)(proposal.path);
|
|
1427
|
+
appendLedger(ledgerPath(hubRoot), {
|
|
1428
|
+
type: "proposal.committed",
|
|
1429
|
+
proposalId,
|
|
1430
|
+
knowledgeId: committed.id,
|
|
1431
|
+
...superseding ? { supersedes: targetId } : {},
|
|
1432
|
+
channel: "panel",
|
|
1433
|
+
note,
|
|
1434
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1435
|
+
});
|
|
1436
|
+
const gitCommit = autoCommit(hubRoot, `approve: ${committed.id}@v${committed.version} ${proposal.frontmatter.title}`);
|
|
1437
|
+
return { knowledgeId: committed.id, version: committed.version, ...superseding ? { superseded: targetId } : {}, git: gitCommit };
|
|
1438
|
+
}
|
|
1439
|
+
function existsSyncSafe(hubRoot, id) {
|
|
1440
|
+
try {
|
|
1441
|
+
getEntry(hubRoot, id);
|
|
1442
|
+
return true;
|
|
1443
|
+
} catch {
|
|
1444
|
+
return false;
|
|
1445
|
+
}
|
|
1446
|
+
}
|
|
1447
|
+
function handleApi(state, method, path, body) {
|
|
1448
|
+
try {
|
|
1449
|
+
switch (`${method} ${path}`) {
|
|
1450
|
+
case "GET /api/status":
|
|
1451
|
+
return ok({
|
|
1452
|
+
hubRoot: state.hubRoot,
|
|
1453
|
+
workspace: state.workspace,
|
|
1454
|
+
lock: lockInfo(state.hubRoot),
|
|
1455
|
+
metrics: state.metrics,
|
|
1456
|
+
acceptedCount: listEntries(state.hubRoot).length
|
|
1457
|
+
});
|
|
1458
|
+
case "GET /api/inbox":
|
|
1459
|
+
return ok({
|
|
1460
|
+
proposals: listProposals(state.hubRoot).map((p) => ({
|
|
1461
|
+
id: p.id,
|
|
1462
|
+
type: p.frontmatter.type,
|
|
1463
|
+
title: p.frontmatter.title,
|
|
1464
|
+
summary: p.frontmatter.summary,
|
|
1465
|
+
tags: p.frontmatter.tags,
|
|
1466
|
+
grade: gradeFor(p.frontmatter.type),
|
|
1467
|
+
path: p.path
|
|
1468
|
+
}))
|
|
1469
|
+
});
|
|
1470
|
+
case "POST /api/propose": {
|
|
1471
|
+
const type = body?.["type"];
|
|
1472
|
+
const title = body?.["title"];
|
|
1473
|
+
const summary = body?.["summary"];
|
|
1474
|
+
const bodyText = body?.["body"];
|
|
1475
|
+
if (typeof type !== "string" || typeof title !== "string" || typeof summary !== "string" || typeof bodyText !== "string") {
|
|
1476
|
+
return bad(400, "propose requires type, title, summary, body");
|
|
1477
|
+
}
|
|
1478
|
+
return withWriteLock(state.hubRoot, () => {
|
|
1479
|
+
const proposal = createProposal(state.hubRoot, {
|
|
1480
|
+
type,
|
|
1481
|
+
title,
|
|
1482
|
+
summary,
|
|
1483
|
+
scope: { level: "project", workspaceId: state.workspace.workspaceId },
|
|
1484
|
+
tags: Array.isArray(body?.["tags"]) ? (body?.["tags"]).map(String) : [],
|
|
1485
|
+
body: bodyText,
|
|
1486
|
+
sourceRefs: Array.isArray(body?.["sourceRefs"]) ? (body?.["sourceRefs"]).map(String) : [`remote:${(/* @__PURE__ */ new Date()).toISOString()}`],
|
|
1487
|
+
supersedes: Array.isArray(body?.["supersedes"]) ? (body?.["supersedes"]).map(String) : void 0,
|
|
1488
|
+
originId: typeof body?.["originId"] === "string" ? body["originId"] : void 0,
|
|
1489
|
+
origin: typeof body?.["origin"] === "string" ? body["origin"] : "remote-hub",
|
|
1490
|
+
actor: "remote"
|
|
1491
|
+
}, { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) });
|
|
1492
|
+
registerWorkspace(state.hubRoot, state.workspace, () => (/* @__PURE__ */ new Date()).toISOString(), readHubConfig, (root, content) => {
|
|
1493
|
+
(0, import_node_fs8.appendFileSync)((0, import_node_path9.join)(root, "hub.yaml"), content, "utf8");
|
|
1494
|
+
});
|
|
1495
|
+
state.index = buildIndex(state.hubRoot, () => (/* @__PURE__ */ new Date()).toISOString());
|
|
1496
|
+
state.metrics = emptyMetrics(state.index);
|
|
1497
|
+
return ok({ proposalId: proposal.id, nextStep: "central review via inbox" });
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
case "POST /api/search": {
|
|
1501
|
+
const query = String(body?.["query"] ?? "");
|
|
1502
|
+
if (query === "")
|
|
1503
|
+
return bad(400, "query is required");
|
|
1504
|
+
const hits = search(state.index, query, {
|
|
1505
|
+
workspaceId: state.workspace.workspaceId,
|
|
1506
|
+
detail: "L1",
|
|
1507
|
+
limit: typeof body?.["limit"] === "number" ? body["limit"] : 10
|
|
1508
|
+
});
|
|
1509
|
+
return ok({ hits });
|
|
1510
|
+
}
|
|
1511
|
+
case "GET /api/entries": {
|
|
1512
|
+
const since = typeof body?.["since"] === "string" ? body["since"] : void 0;
|
|
1513
|
+
const all = listEntries(state.hubRoot, { includeSoftRemoved: true }).map((e) => ({
|
|
1514
|
+
id: e.frontmatter.id,
|
|
1515
|
+
version: e.frontmatter.version,
|
|
1516
|
+
type: e.frontmatter.type,
|
|
1517
|
+
status: e.frontmatter.status,
|
|
1518
|
+
title: e.frontmatter.title,
|
|
1519
|
+
summary: e.frontmatter.summary,
|
|
1520
|
+
scope: e.frontmatter.scope,
|
|
1521
|
+
tags: e.frontmatter.tags,
|
|
1522
|
+
updated: e.frontmatter.updated,
|
|
1523
|
+
path: e.path
|
|
1524
|
+
}));
|
|
1525
|
+
const entries = since === void 0 ? all : all.filter((e) => (e.updated ?? "") > since);
|
|
1526
|
+
return ok({ entries, since: since ?? null, count: entries.length });
|
|
1527
|
+
}
|
|
1528
|
+
case "GET /api/ledger": {
|
|
1529
|
+
const records = readLedger(ledgerPath(state.hubRoot));
|
|
1530
|
+
const limit = typeof body?.["limit"] === "number" ? body["limit"] : 200;
|
|
1531
|
+
return ok({ records: records.slice(-limit).reverse(), total: records.length });
|
|
1532
|
+
}
|
|
1533
|
+
case "GET /api/journal": {
|
|
1534
|
+
const day = typeof body?.["day"] === "string" ? body["day"] : void 0;
|
|
1535
|
+
const entries = readJournal(state.hubRoot, day);
|
|
1536
|
+
return ok({ entries: entries.slice(-200).reverse() });
|
|
1537
|
+
}
|
|
1538
|
+
default:
|
|
1539
|
+
break;
|
|
1540
|
+
}
|
|
1541
|
+
const approveMatch = /^\/api\/inbox\/([A-Za-z0-9-]+)\/approve$/.exec(path);
|
|
1542
|
+
if (approveMatch !== null && method === "POST") {
|
|
1543
|
+
return approve(state, [approveMatch[1] ?? ""], body);
|
|
1544
|
+
}
|
|
1545
|
+
const batchMatch = /^\/api\/inbox\/approve$/.exec(path);
|
|
1546
|
+
if (batchMatch !== null && method === "POST") {
|
|
1547
|
+
const ids = body?.["ids"];
|
|
1548
|
+
if (!Array.isArray(ids) || ids.length === 0)
|
|
1549
|
+
return bad(400, "ids array is required for batch approval");
|
|
1550
|
+
return approve(state, ids.map(String), body);
|
|
1551
|
+
}
|
|
1552
|
+
const rejectMatch = /^\/api\/inbox\/([A-Za-z0-9-]+)\/reject$/.exec(path);
|
|
1553
|
+
if (rejectMatch !== null && method === "POST") {
|
|
1554
|
+
return reject(state, rejectMatch[1] ?? "", body);
|
|
1555
|
+
}
|
|
1556
|
+
const entryMatch = /^\/api\/entries\/([A-Za-z0-9-]+)$/.exec(path);
|
|
1557
|
+
if (entryMatch !== null && method === "GET") {
|
|
1558
|
+
const entry = getEntry(state.hubRoot, entryMatch[1] ?? "");
|
|
1559
|
+
return ok({ frontmatter: entry.frontmatter, body: entry.body, path: entry.path });
|
|
1560
|
+
}
|
|
1561
|
+
const deprecateMatch = /^\/api\/entries\/([A-Za-z0-9-]+)\/deprecate$/.exec(path);
|
|
1562
|
+
if (deprecateMatch !== null && method === "POST") {
|
|
1563
|
+
const reason = typeof body?.["reason"] === "string" && body["reason"] !== "" ? body["reason"] : "deprecated via panel";
|
|
1564
|
+
return withWriteLock(state.hubRoot, () => {
|
|
1565
|
+
deprecateEntry(state.hubRoot, deprecateMatch[1] ?? "", reason, {
|
|
1566
|
+
appendLedger: (root, record) => appendLedger(ledgerPath(root), record)
|
|
1567
|
+
});
|
|
1568
|
+
state.index = buildIndex(state.hubRoot, () => (/* @__PURE__ */ new Date()).toISOString());
|
|
1569
|
+
state.metrics = emptyMetrics(state.index);
|
|
1570
|
+
return ok({ deprecated: deprecateMatch[1] ?? "", reason, git: autoCommit(state.hubRoot, `deprecate: ${deprecateMatch[1]} (${reason})`) });
|
|
1571
|
+
});
|
|
1572
|
+
}
|
|
1573
|
+
const deleteMatch = /^\/api\/entries\/([A-Za-z0-9-]+)\/delete$/.exec(path);
|
|
1574
|
+
if (deleteMatch !== null && method === "POST") {
|
|
1575
|
+
const reason = typeof body?.["reason"] === "string" && body["reason"] !== "" ? body["reason"] : "hard-deleted via panel";
|
|
1576
|
+
return withWriteLock(state.hubRoot, () => {
|
|
1577
|
+
hardDeleteEntry(state.hubRoot, deleteMatch[1] ?? "", reason, {
|
|
1578
|
+
appendLedger: (root, record) => appendLedger(ledgerPath(root), record)
|
|
1579
|
+
});
|
|
1580
|
+
state.index = buildIndex(state.hubRoot, () => (/* @__PURE__ */ new Date()).toISOString());
|
|
1581
|
+
state.metrics = emptyMetrics(state.index);
|
|
1582
|
+
return ok({ deleted: deleteMatch[1] ?? "", reason, git: autoCommit(state.hubRoot, `delete: ${deleteMatch[1]} (${reason})`) });
|
|
1583
|
+
});
|
|
1584
|
+
}
|
|
1585
|
+
const updateMatch = /^\/api\/entries\/([A-Za-z0-9-]+)\/update$/.exec(path);
|
|
1586
|
+
if (updateMatch !== null && method === "POST") {
|
|
1587
|
+
const existing = getEntry(state.hubRoot, updateMatch[1] ?? "");
|
|
1588
|
+
const summary = typeof body?.["summary"] === "string" && body["summary"] !== "" ? body["summary"] : existing.frontmatter.summary;
|
|
1589
|
+
const nextBody = typeof body?.["body"] === "string" ? body["body"] : existing.body;
|
|
1590
|
+
const tags = Array.isArray(body?.["tags"]) ? (body?.["tags"]).map(String) : existing.frontmatter.tags;
|
|
1591
|
+
return withWriteLock(state.hubRoot, () => {
|
|
1592
|
+
const updated = commitKnowledge(state.hubRoot, {
|
|
1593
|
+
id: existing.frontmatter.id,
|
|
1594
|
+
type: existing.frontmatter.type,
|
|
1595
|
+
title: existing.frontmatter.title,
|
|
1596
|
+
summary,
|
|
1597
|
+
scope: existing.frontmatter.scope,
|
|
1598
|
+
tags,
|
|
1599
|
+
body: nextBody,
|
|
1600
|
+
actor: "panel"
|
|
1601
|
+
}, { readSequences, writeSequences, appendLedger: (root, record) => appendLedger(ledgerPath(root), record) });
|
|
1602
|
+
state.index = buildIndex(state.hubRoot, () => (/* @__PURE__ */ new Date()).toISOString());
|
|
1603
|
+
state.metrics = emptyMetrics(state.index);
|
|
1604
|
+
return ok({ updated: updated.id, version: updated.version, git: autoCommit(state.hubRoot, `update: ${updated.id}@v${updated.version}`) });
|
|
1605
|
+
});
|
|
1606
|
+
}
|
|
1607
|
+
return bad(404, `no route: ${method} ${path}`);
|
|
1608
|
+
} catch (error) {
|
|
1609
|
+
if (error instanceof HubError) {
|
|
1610
|
+
const map = {
|
|
1611
|
+
[ErrorCode.E_NOT_FOUND]: 404,
|
|
1612
|
+
[ErrorCode.E_VALIDATION]: 400,
|
|
1613
|
+
[ErrorCode.E_CONFLICT]: 409,
|
|
1614
|
+
[ErrorCode.E_READONLY]: 423,
|
|
1615
|
+
[ErrorCode.E_APPROVAL_REQUIRED]: 403,
|
|
1616
|
+
[ErrorCode.E_HUB_NOT_INITIALIZED]: 404
|
|
1617
|
+
};
|
|
1618
|
+
return bad(map[error.code] ?? 500, error.message, error.details);
|
|
1619
|
+
}
|
|
1620
|
+
return bad(500, error instanceof Error ? error.message : String(error));
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
function approve(state, ids, body) {
|
|
1624
|
+
if (ids.length > 1) {
|
|
1625
|
+
const proposals = listProposals(state.hubRoot);
|
|
1626
|
+
const types = ids.map((id) => proposals.find((p) => p.id === id)?.frontmatter.type);
|
|
1627
|
+
if (types.some((t) => t === void 0))
|
|
1628
|
+
return bad(404, "unknown proposal id in batch");
|
|
1629
|
+
if (types.some((t) => gradeFor(t) === "individual")) {
|
|
1630
|
+
return bad(403, "decision/constraint/api-catalog must be approved individually (graded approval)", {
|
|
1631
|
+
individualTypes: INDIVIDUAL_TYPES
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
const note = typeof body?.["note"] === "string" ? body["note"] : void 0;
|
|
1636
|
+
return withWriteLock(state.hubRoot, () => {
|
|
1637
|
+
const results = [];
|
|
1638
|
+
let firstError = null;
|
|
1639
|
+
for (const id of ids) {
|
|
1640
|
+
try {
|
|
1641
|
+
const committed = commitOne(state.hubRoot, id, note);
|
|
1642
|
+
results.push({ proposalId: id, knowledgeId: committed.knowledgeId, version: committed.version, ...committed.superseded !== void 0 ? { superseded: committed.superseded } : {}, git: committed.git });
|
|
1643
|
+
} catch (error) {
|
|
1644
|
+
if (error instanceof HubError && firstError === null)
|
|
1645
|
+
firstError = error;
|
|
1646
|
+
results.push({ proposalId: id, error: error instanceof Error ? error.message : String(error) });
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
if (ids.length === 1 && firstError !== null) {
|
|
1650
|
+
return bad(httpStatusFor(firstError), firstError.message, firstError.details);
|
|
1651
|
+
}
|
|
1652
|
+
state.index = buildIndex(state.hubRoot, () => (/* @__PURE__ */ new Date()).toISOString());
|
|
1653
|
+
state.metrics = emptyMetrics(state.index);
|
|
1654
|
+
const failed = results.some((r) => r.error !== void 0);
|
|
1655
|
+
return { status: failed ? 207 : 200, body: { results } };
|
|
1656
|
+
});
|
|
1657
|
+
}
|
|
1658
|
+
function httpStatusFor(error) {
|
|
1659
|
+
const map = {
|
|
1660
|
+
[ErrorCode.E_NOT_FOUND]: 404,
|
|
1661
|
+
[ErrorCode.E_VALIDATION]: 400,
|
|
1662
|
+
[ErrorCode.E_CONFLICT]: 409,
|
|
1663
|
+
[ErrorCode.E_READONLY]: 423,
|
|
1664
|
+
[ErrorCode.E_APPROVAL_REQUIRED]: 403,
|
|
1665
|
+
[ErrorCode.E_HUB_NOT_INITIALIZED]: 404
|
|
1666
|
+
};
|
|
1667
|
+
return map[error.code] ?? 500;
|
|
1668
|
+
}
|
|
1669
|
+
function reject(state, id, body) {
|
|
1670
|
+
const proposal = listProposals(state.hubRoot).find((p) => p.id === id);
|
|
1671
|
+
if (proposal === void 0)
|
|
1672
|
+
return bad(404, `pending proposal not found: ${id}`);
|
|
1673
|
+
const note = typeof body?.["note"] === "string" ? body["note"] : void 0;
|
|
1674
|
+
appendLedger(ledgerPath(state.hubRoot), {
|
|
1675
|
+
type: "proposal.rejected",
|
|
1676
|
+
proposalId: id,
|
|
1677
|
+
channel: "panel",
|
|
1678
|
+
note,
|
|
1679
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
1680
|
+
});
|
|
1681
|
+
(0, import_node_fs8.unlinkSync)(proposal.path);
|
|
1682
|
+
return ok({ rejected: id });
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
// ../../dist/transport/http.js
|
|
1686
|
+
function startServer(state, options) {
|
|
1687
|
+
const server = (0, import_node_http.createServer)((req, res) => {
|
|
1688
|
+
void route(state, req, res);
|
|
1689
|
+
});
|
|
1690
|
+
server.listen(options?.port ?? 7777, options?.host ?? "127.0.0.1");
|
|
1691
|
+
return server;
|
|
1692
|
+
}
|
|
1693
|
+
async function route(state, req, res) {
|
|
1694
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
1695
|
+
const path = url.pathname;
|
|
1696
|
+
if (req.method === "GET" && (path === "/" || path === "/panel")) {
|
|
1697
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
1698
|
+
res.end(PANEL_HTML);
|
|
1699
|
+
return;
|
|
1700
|
+
}
|
|
1701
|
+
if (path.startsWith("/api/")) {
|
|
1702
|
+
let body;
|
|
1703
|
+
if (url.searchParams.size > 0)
|
|
1704
|
+
body = Object.fromEntries(url.searchParams.entries());
|
|
1705
|
+
if (req.method === "POST") {
|
|
1706
|
+
const chunks = [];
|
|
1707
|
+
for await (const chunk of req)
|
|
1708
|
+
chunks.push(chunk);
|
|
1709
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
1710
|
+
if (raw !== "") {
|
|
1711
|
+
try {
|
|
1712
|
+
body = { ...body ?? {}, ...JSON.parse(raw) };
|
|
1713
|
+
} catch {
|
|
1714
|
+
res.writeHead(400, { "content-type": "application/json" });
|
|
1715
|
+
res.end(JSON.stringify({ error: "invalid JSON body" }));
|
|
1716
|
+
return;
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
const response = handleApi(state, req.method ?? "GET", path, body);
|
|
1721
|
+
res.writeHead(response.status, { "content-type": "application/json" });
|
|
1722
|
+
res.end(JSON.stringify(response.body));
|
|
1723
|
+
return;
|
|
1724
|
+
}
|
|
1725
|
+
res.writeHead(404, { "content-type": "application/json" });
|
|
1726
|
+
res.end(JSON.stringify({ error: `no route: ${req.method} ${path}` }));
|
|
1727
|
+
}
|
|
1728
|
+
|
|
935
1729
|
// src/host-types.ts
|
|
936
1730
|
function renderJson(_args, value) {
|
|
937
1731
|
return [{ type: "text", text: JSON.stringify(value, null, 2) }];
|
|
@@ -1199,6 +1993,29 @@ function createTools(ctx) {
|
|
|
1199
1993
|
// src/index.ts
|
|
1200
1994
|
var name = "agent-memory-hub-dsh";
|
|
1201
1995
|
var inject = ["tools"];
|
|
1996
|
+
var PANEL_PORT = 7777;
|
|
1997
|
+
function startPanelServer(ctx, root) {
|
|
1998
|
+
try {
|
|
1999
|
+
const state = createApiState(root);
|
|
2000
|
+
const server = startServer(state, { port: PANEL_PORT, host: "127.0.0.1" });
|
|
2001
|
+
server.on("error", (error) => {
|
|
2002
|
+
if (error.code === "EADDRINUSE") {
|
|
2003
|
+
ctx.logger?.info(`agent-memory-hub-dsh: panel port ${PANEL_PORT} already serving (manual serve or another session) \u2014 reusing it`);
|
|
2004
|
+
return;
|
|
2005
|
+
}
|
|
2006
|
+
ctx.logger?.warn(`agent-memory-hub-dsh: panel server error: ${error.message}`);
|
|
2007
|
+
});
|
|
2008
|
+
ctx.logger?.info(`agent-memory-hub-dsh: panel console serving at http://127.0.0.1:${PANEL_PORT}/ (hub: ${root})`);
|
|
2009
|
+
ctx.effect?.(() => () => {
|
|
2010
|
+
try {
|
|
2011
|
+
server.close();
|
|
2012
|
+
} catch {
|
|
2013
|
+
}
|
|
2014
|
+
}, `${name}-panel`);
|
|
2015
|
+
} catch (error) {
|
|
2016
|
+
ctx.logger?.warn(`agent-memory-hub-dsh: panel server failed to start: ${error instanceof Error ? error.message : String(error)}`);
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
1202
2019
|
function apply(ctx, config) {
|
|
1203
2020
|
const root = resolveHubRoot(config);
|
|
1204
2021
|
if (!isHubInitialized(root)) {
|
|
@@ -1207,6 +2024,7 @@ function apply(ctx, config) {
|
|
|
1207
2024
|
);
|
|
1208
2025
|
return;
|
|
1209
2026
|
}
|
|
2027
|
+
startPanelServer(ctx, root);
|
|
1210
2028
|
const hubCtx = createHubContext(config);
|
|
1211
2029
|
const conflict = config?.toolConflict ?? "skip";
|
|
1212
2030
|
const disposers = [];
|