121 lines
5.8 KiB
JavaScript
121 lines
5.8 KiB
JavaScript
import fs from "node:fs";
|
||
import path from "node:path";
|
||
|
||
// Память бренда (BRM-57): факты с уровнем доказательности, кейсы, стадии, вопросы.
|
||
export const LEVELS = ["D", "U", "W", "H", "V"];
|
||
export const BUCKETS = ["verified", "hypothesis", "preference", "decision", "temporary"];
|
||
export const PERMISSIONS = ["yes", "no", "unknown"];
|
||
export const CHECKS = ["checked", "unchecked"];
|
||
export const STAGES = ["concept", "prototype", "pilot", "rollout"];
|
||
export const CASE_FIELDS = ["problem", "scope", "period", "personal_role", "actions", "baseline", "after", "methodology", "evidence", "public_permission", "approved_quote"];
|
||
// Уровни, на которые можно опираться в публичных текстах.
|
||
const SOLID = ["D", "U"];
|
||
|
||
const str = (v) => (v == null ? "" : String(v).trim());
|
||
const isDate = (s) => /^\d{4}-\d{2}-\d{2}$/.test(s) && new Date(s + "T00:00:00Z").toISOString().slice(0, 10) === s;
|
||
|
||
export function normalizeFact(b) {
|
||
return {
|
||
key: str(b.key), bucket: str(b.bucket), title: str(b.title), text: str(b.text), level: str(b.level),
|
||
source: str(b.source), date: str(b.date), permission: str(b.permission) || "unknown", check: str(b.check) || "unchecked",
|
||
claimed: !!b.claimed, forbidden: !!b.forbidden, period: str(b.period), method: str(b.method), stage: str(b.stage), note: str(b.note),
|
||
};
|
||
}
|
||
|
||
export function validateFact(f) {
|
||
if (!/^[\w-]+$/.test(f.key)) return "err.facts.key";
|
||
if (!BUCKETS.includes(f.bucket)) return "err.facts.bucket";
|
||
if (!f.title) return "err.facts.title";
|
||
if (!LEVELS.includes(f.level)) return "err.facts.level";
|
||
if (!f.source) return "err.facts.source";
|
||
if (!isDate(f.date)) return "err.facts.date";
|
||
if (!PERMISSIONS.includes(f.permission)) return "err.facts.permission";
|
||
if (!CHECKS.includes(f.check)) return "err.facts.check";
|
||
if (f.stage && !STAGES.includes(f.stage)) return "err.facts.stage";
|
||
return null;
|
||
}
|
||
|
||
// Можно ли писать это в публичный текст; причины — коды для слов на странице.
|
||
export function publicStatus(f) {
|
||
const why = [];
|
||
if (f.forbidden) why.push("forbidden");
|
||
if (f.revoked) why.push("revoked");
|
||
if (!SOLID.includes(f.level)) why.push("level");
|
||
if (f.check !== "checked") why.push("unchecked");
|
||
if (f.permission !== "yes") why.push("permission");
|
||
if (f.claimed) { if (!f.period) why.push("period"); if (!f.method) why.push("method"); }
|
||
return { ok: why.length === 0, why };
|
||
}
|
||
|
||
export const factView = (f) => ({ ...f, public: publicStatus(f) });
|
||
|
||
export function caseView(c) {
|
||
const missing = CASE_FIELDS.filter((k) => !str(c[k]));
|
||
return { ...c, missing, stageOk: !c.stage || STAGES.includes(c.stage) };
|
||
}
|
||
|
||
export function createFactsStore(file) {
|
||
let data;
|
||
try { data = JSON.parse(fs.readFileSync(file, "utf8")); } catch { data = {}; }
|
||
data.facts ??= []; data.cases ??= []; data.questions ??= [];
|
||
const save = () => {
|
||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||
fs.writeFileSync(file + ".tmp", JSON.stringify(data, null, 2));
|
||
fs.renameSync(file + ".tmp", file);
|
||
};
|
||
const find = (k) => data.facts.find((f) => f.key === k);
|
||
return {
|
||
list: (bucket) => data.facts.filter((f) => !bucket || f.bucket === bucket),
|
||
get: find,
|
||
// Правка не затирает прошлое: прежняя запись уходит в versions.
|
||
upsert(b, { seed = false } = {}) {
|
||
const n = normalizeFact(b); const err = validateFact(n);
|
||
if (err) return { err };
|
||
const old = find(n.key);
|
||
if (old && seed) return { record: old, created: false };
|
||
if (!old) { const r = { ...n, versions: [], revoked: null }; data.facts.push(r); save(); return { record: r, created: true }; }
|
||
const { versions, revoked, ...prev } = old;
|
||
Object.assign(old, n, { versions: [...versions, { ...prev, savedAt: new Date().toISOString() }] });
|
||
save(); return { record: old, created: false };
|
||
},
|
||
revoke(key, reason) {
|
||
const f = find(key);
|
||
if (!f) return { err: "err.facts.notfound" };
|
||
if (!str(reason)) return { err: "err.facts.reason" };
|
||
f.revoked = { at: new Date().toISOString(), reason: str(reason) };
|
||
save(); return { record: f };
|
||
},
|
||
restore(key) {
|
||
const f = find(key); if (!f) return { err: "err.facts.notfound" };
|
||
f.revoked = null; save(); return { record: f };
|
||
},
|
||
cases: () => data.cases,
|
||
getCase: (id) => data.cases.find((c) => c.id === id),
|
||
upsertCase(b) {
|
||
const id = str(b.id);
|
||
if (!/^[\w-]+$/.test(id)) return { err: "err.facts.key" };
|
||
const stage = str(b.stage);
|
||
if (stage && !STAGES.includes(stage)) return { err: "err.facts.stage" };
|
||
const c = { id, title: str(b.title), stage, status: str(b.status) };
|
||
for (const k of CASE_FIELDS) c[k] = str(b[k]);
|
||
const i = data.cases.findIndex((x) => x.id === id);
|
||
if (i < 0) data.cases.push(c); else data.cases[i] = c;
|
||
save(); return { record: c, created: i < 0 };
|
||
},
|
||
seedCase(c) { if (!data.cases.some((x) => x.id === c.id)) this.upsertCase(c); },
|
||
questions: () => data.questions,
|
||
seedQuestion(q) { if (!data.questions.some((x) => x.id === q.id)) { data.questions.push({ ...q, answer: "" }); save(); } },
|
||
// Порция вопросов: 1–3 самых важных открытых (приоритет 1 — самый важный).
|
||
nextQuestions(n = 3) {
|
||
const k = Math.min(3, Math.max(1, Number(n) || 3));
|
||
return data.questions.filter((q) => !q.answer).sort((a, b) => a.priority - b.priority || a.id - b.id).slice(0, k);
|
||
},
|
||
answer(id, text) {
|
||
const q = data.questions.find((x) => x.id === Number(id));
|
||
if (!q) return { err: "err.facts.notfound" };
|
||
if (!str(text)) return { err: "err.facts.answer" };
|
||
q.answer = str(text); save(); return { record: q };
|
||
},
|
||
};
|
||
}
|