wendkeep 0.76.1 → 0.76.2
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/CHANGELOG.md +13 -0
- package/README.en.md +3 -3
- package/README.md +3 -3
- package/docs/en/commands/memory.md +7 -0
- package/docs/pt-BR/commands/memory.md +7 -0
- package/hooks/vault-health.mjs +15 -6
- package/package.json +1 -1
- package/packages/vault/src/memory-schema.mjs +122 -18
- package/packages/vault/src/memory-store.mjs +4 -0
- package/packages/vault/src/validate-memory.mjs +40 -3
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,19 @@ All notable changes to **wendkeep** are documented here. Format based on
|
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project follows
|
|
5
5
|
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
6
|
|
|
7
|
+
## [0.76.2] — 2026-08-21
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- **Projeção SHARED bounded na origem.** O projector agora admite eventos completos de forma
|
|
12
|
+
determinística e priorizada, nunca publica `SHARED_MEMORY.md` acima de 48 linhas/6144 bytes e
|
|
13
|
+
declara as contagens projetada/omitida sem perder a autoridade integral do ledger.
|
|
14
|
+
- **Omissão bounded verificável.** O gate semântico rederiva a seleção esperada; apenas o recorte
|
|
15
|
+
exato é aceito como aviso operacional, enquanto IDs ou contagens divergentes continuam bloqueando.
|
|
16
|
+
- **Recuperação antes de rescope.** Com memória estruturalmente bloqueada, o doctor orienta
|
|
17
|
+
`memory repair` e novo `memory status --gate` antes de voltar ao dry-run, sem recomendar
|
|
18
|
+
`memory rescope --apply` sobre uma projeção inválida.
|
|
19
|
+
|
|
7
20
|
## [0.76.1] — 2026-08-21
|
|
8
21
|
|
|
9
22
|
### Added
|
package/README.en.md
CHANGED
|
@@ -373,7 +373,7 @@ an installation failure.
|
|
|
373
373
|
Hot memory now separates human authorship, operational state, and evidence:
|
|
374
374
|
|
|
375
375
|
- **`CORE.md` is canonical.** It is the short, hand-curated nucleus for durable preferences, active patterns, and open issues; no projector may infer or overwrite it.
|
|
376
|
-
- **`SHARED_MEMORY.md` is generated operational state.** The `Stop` hook turns the session handoff into sanitized events; the projector deterministically reduces the ledger and publishes a verifiable revision, cursor, and hash. Facts are `verified` only with local evidence; unsupported reports remain `reported`, and disagreements become candidates for human judgment.
|
|
376
|
+
- **`SHARED_MEMORY.md` is bounded generated operational state.** The `Stop` hook turns the session handoff into sanitized events; the projector deterministically reduces the ledger and publishes a verifiable revision, cursor, and hash. Admission prioritizes critical operational state and never publishes beyond 48 lines/6 KiB; omitted events remain in the append-only authority and surface only as verifiable counts. Facts are `verified` only with local evidence; unsupported reports remain `reported`, and disagreements become candidates for human judgment.
|
|
377
377
|
- **`MEMORY_EVENTS.jsonl` is the append-only authority.** `Stop` makes events durable in the outbox before acknowledging the attempt; the projector runs outside the registry lock and retries reuse the same IDs. Repeating an identical `event_id`/payload is a no-op; reusing the ID with different bytes is observable corruption.
|
|
378
378
|
- **`MEMORY_CANDIDATES.jsonl` is the curation queue.** Conflicts and legacy content are never silently promoted. `promote` and `reject` record the decision as a new event; promotion preserves the selected event's JSON type, session, activation/epoch, and source turn.
|
|
379
379
|
- **Registers are scoped.** `git.local-head`, handoffs, verdicts, and change status carry project, work-session, change, branch, or worktree scope. Two branches do not create a global conflict; only events in the same scope and causal lineage may advance automatically.
|
|
@@ -389,9 +389,9 @@ Codex uses `session_id`/`turn_id` plus transcript order, with no artificial caus
|
|
|
389
389
|
|
|
390
390
|
### Injection and budgets
|
|
391
391
|
|
|
392
|
-
`CORE.md` is the only manual layer: it accepts up to 40 lines, warns from 35, keeps a 4 KiB ceiling, and caps each line at 320 characters. `SHARED_MEMORY.md` is generated exclusively by the projector and ledger; never edit it to repair state. `brain-inject` delivers the same revision/hash on `startup`, `/clear`, and `/compact` `SessionStart` events, always placing CORE and SHARED before change context. The full envelope is capped at 24 KiB; SHARED reserves up to 6 KiB. Under pressure, lessons are removed first, then non-current changes. CORE and SHARED
|
|
392
|
+
`CORE.md` is the only manual layer: it accepts up to 40 lines, warns from 35, keeps a 4 KiB ceiling, and caps each line at 320 characters. `SHARED_MEMORY.md` is generated exclusively by the projector and ledger; never edit it to repair state. `brain-inject` delivers the same revision/hash on `startup`, `/clear`, and `/compact` `SessionStart` events, always placing CORE and SHARED before change context. The full envelope is capped at 24 KiB; SHARED reserves up to 48 lines/6 KiB. Under pressure, lessons are removed first, then non-current changes. CORE is never sliced and SHARED admits deterministic whole events rather than prefix-slicing; a missing, invalid, or over-budget layer becomes a visible, repairable `<wk_memory_error>`.
|
|
393
393
|
|
|
394
|
-
`memory status --gate` and `validate-memory --vault` also check semantic coverage: they report a code, counts, and active/projected/missing keys. An empty v2 bundle is neutral; a missing
|
|
394
|
+
`memory status --gate` and `validate-memory --vault` also check semantic coverage: they report a code, counts, and active/projected/missing keys. An empty v2 bundle is neutral; a bounded omission that exactly reproduces ledger selection is an operational warning. An arbitrarily missing event, false count, placeholders as the only content, or an unresolved decision link remains explicitly degraded/blocking without printing memory values.
|
|
395
395
|
|
|
396
396
|
`DIGEST.md` is no longer the operational handoff: it remains the `/brain-recall` bridge and legacy-vault fallback. A vault without SHARED receives CORE+DIGEST with a deprecation warning; migrate during the compatibility window:
|
|
397
397
|
|
package/README.md
CHANGED
|
@@ -373,7 +373,7 @@ an installation failure.
|
|
|
373
373
|
Hot memory now separates human authorship, operational state, and evidence:
|
|
374
374
|
|
|
375
375
|
- **`CORE.md` is canonical.** It is the short, hand-curated nucleus for durable preferences, active patterns, and open issues; no projector may infer or overwrite it.
|
|
376
|
-
- **`SHARED_MEMORY.md` is generated operational state.** The `Stop` hook turns the session handoff into sanitized events; the projector deterministically reduces the ledger and publishes a verifiable revision, cursor, and hash. Facts are `verified` only with local evidence; unsupported reports remain `reported`, and disagreements become candidates for human judgment.
|
|
376
|
+
- **`SHARED_MEMORY.md` is bounded generated operational state.** The `Stop` hook turns the session handoff into sanitized events; the projector deterministically reduces the ledger and publishes a verifiable revision, cursor, and hash. Admission prioritizes critical operational state and never publishes beyond 48 lines/6 KiB; omitted events remain in the append-only authority and surface only as verifiable counts. Facts are `verified` only with local evidence; unsupported reports remain `reported`, and disagreements become candidates for human judgment.
|
|
377
377
|
- **`MEMORY_EVENTS.jsonl` is the append-only authority.** `Stop` makes events durable in the outbox before acknowledging the attempt; the projector runs outside the registry lock and retries reuse the same IDs. Repeating an identical `event_id`/payload is a no-op; reusing the ID with different bytes is observable corruption.
|
|
378
378
|
- **`MEMORY_CANDIDATES.jsonl` is the curation queue.** Conflicts and legacy content are never silently promoted. `promote` and `reject` record the decision as a new event; promotion preserves the selected event's JSON type, session, activation/epoch, and source turn.
|
|
379
379
|
- **Registers are scoped.** `git.local-head`, handoffs, verdicts, and change status carry project, work-session, change, branch, or worktree scope. Two branches do not create a global conflict; only events in the same scope and causal lineage may advance automatically.
|
|
@@ -389,9 +389,9 @@ Codex uses `session_id`/`turn_id` plus transcript order, with no artificial caus
|
|
|
389
389
|
|
|
390
390
|
### Injection and budgets
|
|
391
391
|
|
|
392
|
-
`CORE.md` is the only manual layer: it accepts up to 40 lines, warns from 35, keeps a 4 KiB ceiling, and caps each line at 320 characters. `SHARED_MEMORY.md` is generated exclusively by the projector and ledger; never edit it to repair state. `brain-inject` delivers the same revision/hash on `startup`, `/clear`, and `/compact` `SessionStart` events, always placing CORE and SHARED before change context. The full envelope is capped at 24 KiB; SHARED reserves up to 6 KiB. Under pressure, lessons are removed first, then non-current changes. CORE and SHARED
|
|
392
|
+
`CORE.md` is the only manual layer: it accepts up to 40 lines, warns from 35, keeps a 4 KiB ceiling, and caps each line at 320 characters. `SHARED_MEMORY.md` is generated exclusively by the projector and ledger; never edit it to repair state. `brain-inject` delivers the same revision/hash on `startup`, `/clear`, and `/compact` `SessionStart` events, always placing CORE and SHARED before change context. The full envelope is capped at 24 KiB; SHARED reserves up to 48 lines/6 KiB. Under pressure, lessons are removed first, then non-current changes. CORE is never sliced and SHARED admits deterministic whole events rather than prefix-slicing; a missing, invalid, or over-budget layer becomes a visible, repairable `<wk_memory_error>`.
|
|
393
393
|
|
|
394
|
-
`memory status --gate` and `validate-memory --vault` also check semantic coverage: they report a code, counts, and active/projected/missing keys. An empty v2 bundle is neutral; a missing
|
|
394
|
+
`memory status --gate` and `validate-memory --vault` also check semantic coverage: they report a code, counts, and active/projected/missing keys. An empty v2 bundle is neutral; a bounded omission that exactly reproduces ledger selection is an operational warning. An arbitrarily missing event, false count, placeholders as the only content, or an unresolved decision link remains explicitly degraded/blocking without printing memory values.
|
|
395
395
|
|
|
396
396
|
`DIGEST.md` is no longer the operational handoff: it remains the `/brain-recall` bridge and legacy-vault fallback. A vault without SHARED receives CORE+DIGEST with a deprecation warning; migrate during the compatibility window:
|
|
397
397
|
|
|
@@ -98,12 +98,19 @@ npx wendkeep validate-memory --vault <v2-vault>
|
|
|
98
98
|
and its successor. Replay is CORE-aware, checkpoints use the physical ledger cursor, and the
|
|
99
99
|
command neither rewrites ledger/CORE/notes nor consumes the outbox. Retrying the same applied
|
|
100
100
|
decision is idempotent.
|
|
101
|
+
- The projector deterministically admits whole events, prioritizing critical operational state up
|
|
102
|
+
to 48 lines/6144 bytes. `projection_mode`, `projected_events`, and `omitted_events` make the
|
|
103
|
+
selection verifiable; revision, cursor, and `state_hash` still cover the complete ledger. The
|
|
104
|
+
gate accepts only omissions that re-derive exactly from the same policy.
|
|
101
105
|
- `memory rescope` is a dry run by default and lists only planned IDs, keys, and scopes. With
|
|
102
106
|
`--apply`, it appends explicit project, work-session, change, branch, or worktree events while
|
|
103
107
|
preserving historic bytes as the ledger prefix. Legacy `handoff.latest` events inside candidates
|
|
104
108
|
are also rescoped individually when they carry proven session identity, separating independent
|
|
105
109
|
workflows without selecting a winner. Ambiguities that remain inside one scope stay under human
|
|
106
110
|
curation; retry returns `unchanged`.
|
|
111
|
+
If doctor reports structurally blocked memory, run `memory repair` first, confirm a green
|
|
112
|
+
`memory status --gate`, and only then return to the dry run; never apply rescope over an invalid
|
|
113
|
+
projection.
|
|
107
114
|
- Registers such as `git.local-head`, `handoff.latest`, `quality.latest-*`, and
|
|
108
115
|
`change.<slug>.status` compete only inside the same scope. Automatic resolution still requires
|
|
109
116
|
the same project and causal lineage; incompatible decisions, constraints, and blockers remain
|
|
@@ -98,12 +98,19 @@ npx wendkeep validate-memory --vault <cofre-v2>
|
|
|
98
98
|
do attempt exato, salva backup do registry e limita a mutação ao attempt ambíguo e à sucessora.
|
|
99
99
|
O replay é CORE-aware, usa cursor físico do ledger no checkpoint e não reescreve ledger, CORE ou
|
|
100
100
|
notas, nem consome a outbox. Repetir a mesma decisão aplicada é idempotente.
|
|
101
|
+
- O projector admite eventos completos de forma determinística e prioriza estado operacional
|
|
102
|
+
crítico até o limite de 48 linhas/6144 bytes. `projection_mode`, `projected_events` e
|
|
103
|
+
`omitted_events` tornam o recorte verificável; revision, cursor e `state_hash` continuam cobrindo
|
|
104
|
+
o ledger integral. O gate aceita somente a omissão que rederiva exatamente da mesma política.
|
|
101
105
|
- `memory rescope` é dry-run por padrão e lista somente IDs, chaves e escopos planejados. Com
|
|
102
106
|
`--apply`, anexa eventos explícitos de projeto, work session, change, branch ou worktree e mantém
|
|
103
107
|
os bytes históricos como prefixo do ledger. Eventos legados de `handoff.latest` que participam
|
|
104
108
|
de candidates também são reescopados individualmente quando possuem identidade de sessão
|
|
105
109
|
comprovável: isso separa workflows independentes sem selecionar vencedor. Ambiguidades que
|
|
106
110
|
permanecem no mesmo escopo continuam sob curadoria; uma repetição retorna `unchanged`.
|
|
111
|
+
Se o doctor indicar memória estruturalmente bloqueada, execute primeiro `memory repair`, confirme
|
|
112
|
+
`memory status --gate` verde e só então volte ao dry-run; não aplique rescope sobre uma projeção
|
|
113
|
+
inválida.
|
|
107
114
|
- Registradores como `git.local-head`, `handoff.latest`, `quality.latest-*` e
|
|
108
115
|
`change.<slug>.status` só competem dentro do mesmo escopo. Resolução automática ainda exige o
|
|
109
116
|
mesmo projeto e linhagem causal; decisões, constraints e blockers incompatíveis permanecem sob
|
package/hooks/vault-health.mjs
CHANGED
|
@@ -523,12 +523,21 @@ export function checkMemoryBundle(vaultBase, { registry } = {}) {
|
|
|
523
523
|
const label = historicalHandoffs.length === 1
|
|
524
524
|
? '1 handoff histórico reparável'
|
|
525
525
|
: `${historicalHandoffs.length} handoffs históricos reparáveis`;
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
526
|
+
if (!bundle.ok) {
|
|
527
|
+
warnings.push(
|
|
528
|
+
`${label}; a memória está bloqueada e rescope não deve ampliar uma projeção inválida. `
|
|
529
|
+
+ `Repare primeiro: ${memoryRepairCommand(vaultBase)}. `
|
|
530
|
+
+ `Confirme a recuperação: ${memoryStatusCommand(vaultBase)}. `
|
|
531
|
+
+ 'Somente depois de um gate verde reexecute o doctor para revisar o dry-run de rescope.',
|
|
532
|
+
);
|
|
533
|
+
} else {
|
|
534
|
+
warnings.push(
|
|
535
|
+
`${label}; sessões de origem estão encerradas e nenhuma versão precisa virar estado atual. `
|
|
536
|
+
+ `Execute primeiro o dry-run: ${memoryRescopeCommand(vaultBase)}. `
|
|
537
|
+
+ `Se a prévia estiver correta: ${memoryRescopeCommand(vaultBase, { apply: true })}. `
|
|
538
|
+
+ `Dívida restante: ${memoryCurateAllCommand(vaultBase)}.`,
|
|
539
|
+
);
|
|
540
|
+
}
|
|
532
541
|
}
|
|
533
542
|
if (outbox.count) warnings.push(`${outbox.count} evento(s) pendente(s) na outbox; execute o projector quando seguro.`);
|
|
534
543
|
if (ordinaryCandidates.length) warnings.push(`${ordinaryCandidates.length} candidate(s) aguardando curadoria humana.`);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wendkeep",
|
|
3
|
-
"version": "0.76.
|
|
3
|
+
"version": "0.76.2",
|
|
4
4
|
"description": "Vault-first persistent memory for AI coding agents, with an optional profile-aware governance runtime: OFF, FLOW, GUIDE, GOVERN, or ASSURE. Local-first and agent-agnostic (Claude Code, Codex, Cursor…).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"workspaces": [
|
|
@@ -14,6 +14,17 @@ export const SHARED_SECTIONS = Object.freeze([
|
|
|
14
14
|
'Último Handoff',
|
|
15
15
|
]);
|
|
16
16
|
|
|
17
|
+
const SHARED_ADMISSION_SECTIONS = Object.freeze([
|
|
18
|
+
'Bloqueios',
|
|
19
|
+
'Objetivo Atual',
|
|
20
|
+
'Restrições Ativas',
|
|
21
|
+
'Decisões em Vigor',
|
|
22
|
+
'Próximas Ações',
|
|
23
|
+
'Riscos Conhecidos',
|
|
24
|
+
'Último Handoff',
|
|
25
|
+
'Estado Entregue',
|
|
26
|
+
]);
|
|
27
|
+
|
|
17
28
|
const AUTHORITIES = new Set(['verified', 'reported', 'candidate']);
|
|
18
29
|
const OPERATIONS = new Set(['assert', 'replace', 'add', 'remove']);
|
|
19
30
|
const ISO_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/;
|
|
@@ -197,29 +208,63 @@ function defaultInstant(events) {
|
|
|
197
208
|
return instants.at(-1) || new Date(0).toISOString();
|
|
198
209
|
}
|
|
199
210
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
211
|
+
function authorityPriority(authority) {
|
|
212
|
+
if (authority === 'verified') return 0;
|
|
213
|
+
if (authority === 'reported') return 1;
|
|
214
|
+
return 2;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function compareProjectionEvents(left, right) {
|
|
218
|
+
return authorityPriority(left?.authority) - authorityPriority(right?.authority)
|
|
219
|
+
|| String(right?.observed_at || '').localeCompare(String(left?.observed_at || ''))
|
|
220
|
+
|| String(left?.projection_key || left?.memory_key || '').localeCompare(
|
|
221
|
+
String(right?.projection_key || right?.memory_key || ''),
|
|
222
|
+
)
|
|
223
|
+
|| String(left?.event_id || '').localeCompare(String(right?.event_id || ''));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function admissionOrder(events) {
|
|
227
|
+
const grouped = new Map(SHARED_ADMISSION_SECTIONS.map((section) => [section, []]));
|
|
228
|
+
for (const event of events) grouped.get(sectionFor(event?.memory_key)).push(event);
|
|
229
|
+
for (const bucket of grouped.values()) bucket.sort(compareProjectionEvents);
|
|
230
|
+
|
|
231
|
+
const ordered = [];
|
|
232
|
+
for (let round = 0; ; round += 1) {
|
|
233
|
+
let admitted = false;
|
|
234
|
+
for (const section of SHARED_ADMISSION_SECTIONS) {
|
|
235
|
+
const event = grouped.get(section)[round];
|
|
236
|
+
if (!event) continue;
|
|
237
|
+
ordered.push(event);
|
|
238
|
+
admitted = true;
|
|
239
|
+
}
|
|
240
|
+
if (!admitted) return ordered;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function renderSharedMemoryContent({
|
|
245
|
+
revision,
|
|
246
|
+
eventCursor,
|
|
247
|
+
allEvents,
|
|
248
|
+
projectedEvents,
|
|
205
249
|
stateHash,
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
}
|
|
209
|
-
const safeEvents = Array.isArray(events) ? events : [];
|
|
210
|
-
const updated = updatedAt || defaultInstant(safeEvents);
|
|
211
|
-
const review = reviewAfter || new Date(Date.parse(updated) + (7 * 24 * 60 * 60 * 1000)).toISOString();
|
|
250
|
+
updated,
|
|
251
|
+
review,
|
|
252
|
+
}) {
|
|
212
253
|
const grouped = new Map(SHARED_SECTIONS.map((section) => [section, []]));
|
|
213
|
-
for (const event of
|
|
254
|
+
for (const event of projectedEvents) grouped.get(sectionFor(event.memory_key)).push(eventLine(event));
|
|
255
|
+
const omittedEvents = allEvents.length - projectedEvents.length;
|
|
214
256
|
|
|
215
257
|
const lines = [
|
|
216
258
|
'---',
|
|
217
259
|
'schema_version: 2',
|
|
218
260
|
`revision: ${Number.isInteger(revision) ? revision : 0}`,
|
|
219
261
|
`event_cursor: ${sanitizeMemoryText(eventCursor || 'none')}`,
|
|
220
|
-
`state_hash: ${sanitizeMemoryText(stateHash || hashProjection(
|
|
262
|
+
`state_hash: ${sanitizeMemoryText(stateHash || hashProjection(allEvents))}`,
|
|
221
263
|
`updated_at: ${sanitizeMemoryText(updated)}`,
|
|
222
264
|
`review_after: ${sanitizeMemoryText(review)}`,
|
|
265
|
+
`projection_mode: ${omittedEvents ? 'bounded' : 'complete'}`,
|
|
266
|
+
`projected_events: ${projectedEvents.length}`,
|
|
267
|
+
`omitted_events: ${omittedEvents}`,
|
|
223
268
|
'---',
|
|
224
269
|
'',
|
|
225
270
|
'# SHARED_MEMORY — projeção operacional gerada',
|
|
@@ -231,6 +276,45 @@ export function renderSharedMemory({
|
|
|
231
276
|
return `${lines.join('\n').trimEnd()}\n`;
|
|
232
277
|
}
|
|
233
278
|
|
|
279
|
+
function actualLineCount(text) {
|
|
280
|
+
const lines = text.split('\n');
|
|
281
|
+
return text.endsWith('\n') ? lines.length - 1 : lines.length;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function sharedFits(content) {
|
|
285
|
+
return actualLineCount(content) <= SHARED_LIMITS.lines
|
|
286
|
+
&& Buffer.byteLength(content, 'utf8') <= SHARED_LIMITS.bytes;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Render the generated operational projection. Inputs are sanitized a second time. */
|
|
290
|
+
export function renderSharedMemory({
|
|
291
|
+
revision = 0,
|
|
292
|
+
eventCursor = 'none',
|
|
293
|
+
events = [],
|
|
294
|
+
stateHash,
|
|
295
|
+
updatedAt,
|
|
296
|
+
reviewAfter,
|
|
297
|
+
} = {}) {
|
|
298
|
+
const safeEvents = Array.isArray(events) ? events : [];
|
|
299
|
+
const updated = updatedAt || defaultInstant(safeEvents);
|
|
300
|
+
const review = reviewAfter || new Date(Date.parse(updated) + (7 * 24 * 60 * 60 * 1000)).toISOString();
|
|
301
|
+
const render = (projectedEvents) => renderSharedMemoryContent({
|
|
302
|
+
revision,
|
|
303
|
+
eventCursor,
|
|
304
|
+
allEvents: safeEvents,
|
|
305
|
+
projectedEvents,
|
|
306
|
+
stateHash,
|
|
307
|
+
updated,
|
|
308
|
+
review,
|
|
309
|
+
});
|
|
310
|
+
const projectedEvents = [];
|
|
311
|
+
for (const event of admissionOrder(safeEvents)) {
|
|
312
|
+
const trial = [...projectedEvents, event];
|
|
313
|
+
if (sharedFits(render(trial))) projectedEvents.push(event);
|
|
314
|
+
}
|
|
315
|
+
return render(projectedEvents);
|
|
316
|
+
}
|
|
317
|
+
|
|
234
318
|
function parseScalar(value) {
|
|
235
319
|
if (/^-?\d+$/.test(value)) return Number(value);
|
|
236
320
|
return value;
|
|
@@ -278,11 +362,6 @@ export function parseSharedMemory(content) {
|
|
|
278
362
|
return { ok: errors.length === 0, errors, metadata, sections };
|
|
279
363
|
}
|
|
280
364
|
|
|
281
|
-
function actualLineCount(text) {
|
|
282
|
-
const lines = text.split('\n');
|
|
283
|
-
return text.endsWith('\n') ? lines.length - 1 : lines.length;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
365
|
export function validateSharedMemory(content, { eventIds } = {}) {
|
|
287
366
|
const text = String(content ?? '').replace(/\r\n/g, '\n');
|
|
288
367
|
const parsed = parseSharedMemory(text);
|
|
@@ -306,6 +385,31 @@ export function validateSharedMemory(content, { eventIds } = {}) {
|
|
|
306
385
|
for (const key of ['event_cursor', 'state_hash', 'updated_at', 'review_after']) {
|
|
307
386
|
if (typeof metadata[key] !== 'string' || !metadata[key]) errors.push(`${key} é obrigatório.`);
|
|
308
387
|
}
|
|
388
|
+
const projectionFields = ['projection_mode', 'projected_events', 'omitted_events'];
|
|
389
|
+
const projectionFieldCount = projectionFields.filter((key) => metadata[key] !== undefined).length;
|
|
390
|
+
if (projectionFieldCount && projectionFieldCount !== projectionFields.length) {
|
|
391
|
+
errors.push('Metadados bounded incompletos: projection_mode, projected_events e omitted_events são inseparáveis.');
|
|
392
|
+
} else if (projectionFieldCount === projectionFields.length) {
|
|
393
|
+
const projectedEventLines = [...parsed.sections.values()].flat()
|
|
394
|
+
.filter((line) => /^\s*-\s+\[[^\]]+\]/.test(line)).length;
|
|
395
|
+
if (!['complete', 'bounded'].includes(metadata.projection_mode)) {
|
|
396
|
+
errors.push('projection_mode deve ser complete ou bounded.');
|
|
397
|
+
}
|
|
398
|
+
if (!Number.isInteger(metadata.projected_events) || metadata.projected_events < 0) {
|
|
399
|
+
errors.push('projected_events deve ser inteiro não negativo.');
|
|
400
|
+
} else if (metadata.projected_events !== projectedEventLines) {
|
|
401
|
+
errors.push(`projected_events declara ${metadata.projected_events}, mas SHARED contém ${projectedEventLines} evento(s).`);
|
|
402
|
+
}
|
|
403
|
+
if (!Number.isInteger(metadata.omitted_events) || metadata.omitted_events < 0) {
|
|
404
|
+
errors.push('omitted_events deve ser inteiro não negativo.');
|
|
405
|
+
}
|
|
406
|
+
if (metadata.projection_mode === 'complete' && metadata.omitted_events !== 0) {
|
|
407
|
+
errors.push('projection_mode complete exige omitted_events igual a 0.');
|
|
408
|
+
}
|
|
409
|
+
if (metadata.projection_mode === 'bounded' && !(metadata.omitted_events > 0)) {
|
|
410
|
+
errors.push('projection_mode bounded exige omitted_events maior que 0.');
|
|
411
|
+
}
|
|
412
|
+
}
|
|
309
413
|
for (const key of ['updated_at', 'review_after']) {
|
|
310
414
|
if (typeof metadata[key] === 'string'
|
|
311
415
|
&& (!ISO_INSTANT.test(metadata[key]) || Number.isNaN(Date.parse(metadata[key])))) {
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
} from 'node:fs';
|
|
11
11
|
import { join } from 'node:path';
|
|
12
12
|
import {
|
|
13
|
+
parseSharedMemory,
|
|
13
14
|
renderSharedMemory,
|
|
14
15
|
sanitizeMemoryText,
|
|
15
16
|
validateMemoryEvent,
|
|
@@ -1007,6 +1008,7 @@ export function prepareMemoryProjection(vaultBase, allEvents) {
|
|
|
1007
1008
|
stateHash: reduced.stateHash,
|
|
1008
1009
|
updatedAt,
|
|
1009
1010
|
});
|
|
1011
|
+
const sharedMetadata = parseSharedMemory(shared).metadata;
|
|
1010
1012
|
const candidates = reduced.candidates.map((item) => canonicalMemoryJson(item)).join('\n')
|
|
1011
1013
|
+ (reduced.candidates.length ? '\n' : '');
|
|
1012
1014
|
return {
|
|
@@ -1018,6 +1020,8 @@ export function prepareMemoryProjection(vaultBase, allEvents) {
|
|
|
1018
1020
|
stateHash: reduced.stateHash,
|
|
1019
1021
|
checkpoint: reduced.checkpoint,
|
|
1020
1022
|
candidates: reduced.candidates.length,
|
|
1023
|
+
projectedEvents: sharedMetadata.projected_events ?? reduced.activeEvents.length,
|
|
1024
|
+
omittedEvents: sharedMetadata.omitted_events ?? 0,
|
|
1021
1025
|
};
|
|
1022
1026
|
}
|
|
1023
1027
|
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { readdirSync, readFileSync } from 'node:fs';
|
|
2
2
|
import { basename, join, relative } from 'node:path';
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
parseSharedMemory, renderSharedMemory, sanitizeMemoryText, validateMemoryEvent, validateSharedMemory,
|
|
5
|
+
} from './memory-schema.mjs';
|
|
4
6
|
import { deriveMemoryProjection } from './memory-store.mjs';
|
|
5
7
|
import { assertVaultPathSafe } from './vault-path-safety.mjs';
|
|
6
8
|
import { validateCore } from './validate-core.mjs';
|
|
@@ -161,6 +163,10 @@ function sharedEventIds(content) {
|
|
|
161
163
|
return ids;
|
|
162
164
|
}
|
|
163
165
|
|
|
166
|
+
function sameStringSet(left, right) {
|
|
167
|
+
return left.size === right.size && [...left].every((value) => right.has(value));
|
|
168
|
+
}
|
|
169
|
+
|
|
164
170
|
function walkDecisionFiles(root, vaultBase, output = []) {
|
|
165
171
|
let entries;
|
|
166
172
|
try { entries = readdirSync(root, { withFileTypes: true }); } catch { return output; }
|
|
@@ -255,13 +261,41 @@ function semanticMemoryHealth(vaultBase, { ledger, shared, candidates }) {
|
|
|
255
261
|
const errors = [];
|
|
256
262
|
const warnings = [];
|
|
257
263
|
const codes = [];
|
|
264
|
+
const metadata = shared.metadata || {};
|
|
265
|
+
const boundedDeclared = metadata.projection_mode === 'bounded';
|
|
266
|
+
let boundedProjection = false;
|
|
267
|
+
if (boundedDeclared) {
|
|
268
|
+
const expectedContent = renderSharedMemory({
|
|
269
|
+
revision: metadata.revision,
|
|
270
|
+
eventCursor: metadata.event_cursor,
|
|
271
|
+
stateHash: metadata.state_hash,
|
|
272
|
+
updatedAt: metadata.updated_at,
|
|
273
|
+
reviewAfter: metadata.review_after,
|
|
274
|
+
events: replay.activeEvents,
|
|
275
|
+
});
|
|
276
|
+
const expectedIds = sharedEventIds(expectedContent);
|
|
277
|
+
const expectedMetadata = parseSharedMemory(expectedContent).metadata;
|
|
278
|
+
boundedProjection = sameStringSet(projectedIds, expectedIds)
|
|
279
|
+
&& metadata.projected_events === expectedMetadata.projected_events
|
|
280
|
+
&& metadata.omitted_events === expectedMetadata.omitted_events;
|
|
281
|
+
if (!boundedProjection) {
|
|
282
|
+
codes.push('MEMORY_SEMANTIC_COVERAGE_MISSING');
|
|
283
|
+
errors.push('[MEMORY_SEMANTIC_COVERAGE_MISSING] SHARED declara bounded, mas IDs ou contagens não reproduzem a seleção do ledger.');
|
|
284
|
+
}
|
|
285
|
+
}
|
|
258
286
|
|
|
259
287
|
if (missingKeys.length && placeholderOnly) {
|
|
260
288
|
codes.push('MEMORY_SEMANTIC_PLACEHOLDER_ONLY');
|
|
261
289
|
errors.push(`[MEMORY_SEMANTIC_PLACEHOLDER_ONLY] SHARED contém somente placeholders para ${activeKeys.length} chave(s) ativa(s); candidates=${candidateCount}.`);
|
|
262
290
|
} else if (missingKeys.length) {
|
|
263
|
-
|
|
264
|
-
|
|
291
|
+
if (boundedProjection) {
|
|
292
|
+
warnings.push(`[MEMORY_SEMANTIC_BOUNDED_PROJECTION] SHARED omite deterministicamente ${metadata.omitted_events} evento(s) do ledger dentro do budget.`);
|
|
293
|
+
} else if (!boundedDeclared) {
|
|
294
|
+
codes.push('MEMORY_SEMANTIC_COVERAGE_MISSING');
|
|
295
|
+
errors.push(`[MEMORY_SEMANTIC_COVERAGE_MISSING] SHARED não cobre ${missingKeys.length} chave(s) ativa(s): ${missingKeys.join(', ')}.`);
|
|
296
|
+
}
|
|
297
|
+
} else if (boundedProjection) {
|
|
298
|
+
warnings.push(`[MEMORY_SEMANTIC_BOUNDED_PROJECTION] SHARED omite deterministicamente ${metadata.omitted_events} evento(s) do ledger dentro do budget.`);
|
|
265
299
|
}
|
|
266
300
|
if (unresolvedLinks.length) {
|
|
267
301
|
codes.push('MEMORY_SEMANTIC_DECISION_LINK_UNRESOLVED');
|
|
@@ -280,6 +314,9 @@ function semanticMemoryHealth(vaultBase, { ledger, shared, candidates }) {
|
|
|
280
314
|
} else if (codes.length) {
|
|
281
315
|
status = 'degraded';
|
|
282
316
|
code = codes[0];
|
|
317
|
+
} else if (boundedProjection) {
|
|
318
|
+
status = 'bounded';
|
|
319
|
+
code = 'MEMORY_SEMANTIC_BOUNDED_PROJECTION';
|
|
283
320
|
}
|
|
284
321
|
|
|
285
322
|
return {
|