@staix/vault-mem 0.11.0 → 0.12.1
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 +16 -0
- package/README.md +17 -2
- package/bin/vmem.js +5 -1
- package/package.json +2 -1
- package/skills/_shared/vault-adapter.md +131 -0
- package/skills/skill-mine/SKILL.md +52 -0
- package/skills/skill-mine/vocab/actions.yaml +110 -0
- package/skills/skill-mine/vocab/objects.yaml +123 -0
- package/skills/vault-connect/SKILL.md +75 -0
- package/skills/vault-enrich/SKILL.md +31 -0
- package/skills/vault-extract/README.md +20 -0
- package/skills/vault-extract/SKILL.md +139 -0
- package/skills/vault-graph/SKILL.md +120 -0
- package/skills/vault-learn/SKILL.md +111 -0
- package/skills/vault-lint/README.md +32 -0
- package/skills/vault-lint/SKILL.md +137 -0
- package/skills/vault-lint/references/lint-output.md +97 -0
- package/skills/vault-lint/references/vault-scope-rules.md +26 -0
- package/skills/vault-lint/references/work-scope-checks.md +71 -0
- package/skills/vault-refactor/SKILL.md +112 -0
- package/skills/vault-remember/SKILL.md +38 -0
- package/skills/vault-rethink/README.md +15 -0
- package/skills/vault-rethink/SKILL.md +58 -0
- package/skills/vault-stats/SKILL.md +49 -0
- package/skills/vault-sync/README.md +15 -0
- package/skills/vault-sync/SKILL.md +195 -0
- package/skills/vault-sync/references/r4-method-evidence.md +12 -0
- package/skills/vault-update/SKILL.md +68 -0
- package/skills/vmem-status/SKILL.md +30 -0
- package/src/amem/host-api.ts +5 -1
- package/src/analysis-input.ts +15 -0
- package/src/analysis-types.ts +3 -1
- package/src/assertion-policy.ts +4 -2
- package/src/assertions.ts +48 -8
- package/src/cli-output.ts +10 -3
- package/src/cli.ts +29 -3
- package/src/commands-table.ts +3 -1
- package/src/config.ts +21 -7
- package/src/enrichment-query.ts +65 -0
- package/src/enrichment-search.ts +69 -0
- package/src/enrichment-store.ts +197 -0
- package/src/enrichment.ts +245 -0
- package/src/graph-evidence.ts +2 -2
- package/src/index.ts +9 -0
- package/src/mcp-vault.ts +46 -8
- package/src/proposal-provider.ts +3 -2
- package/src/proposals.ts +10 -4
- package/src/read-output.ts +1 -1
- package/src/registry.ts +57 -2
- package/src/setup.ts +12 -3
- package/src/skills-install.ts +216 -0
- package/src/ui/panel-types.ts +55 -0
- package/src/ui/panel.js +76 -0
- package/src/ui/plugin.ts +95 -5
- package/src/vault-graph.ts +15 -7
- package/src/vault-index.ts +17 -0
- package/src/vault-lint.ts +12 -4
- package/src/write-operations.ts +38 -1
- package/src/write-types.ts +1 -0
- package/src/write-validation.ts +2 -1
- package/src/writer.ts +1 -1
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vault-sync
|
|
3
|
+
trigger: /vault-sync
|
|
4
|
+
description: Scan work/ for changes, or take an explicit list of work sources, and propose vault extractions with confirmation
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# /vault-sync [scope] [path...]
|
|
8
|
+
|
|
9
|
+
> Before the first vmem call, read `references/vault-adapter.md` §Runtime Discovery and select and bind the vmem vault id; pass it as `vault` on every vmem tool call and as the `<vault>` argument of every `vmem` CLI command.
|
|
10
|
+
|
|
11
|
+
Scan work/ for new or changed content and propose vault extractions. Nothing is created without explicit user confirmation. Without a workspace, use `targets` with explicit source paths; skip workspace scans, registry and entity-resolution steps, task-log promotion and timestamp updates, and report the skipped steps. If no targets were supplied, ask for them.
|
|
12
|
+
|
|
13
|
+
## Input
|
|
14
|
+
- scope (optional): "full" (all work/), "meetings" (meetings only), "projects" (projects only), "diff" (git diff only), "targets" (the work files or directories that follow, no scan)
|
|
15
|
+
- Default: "full"
|
|
16
|
+
- Single work source: call `/vault-extract` directly. A work `inbox/` item is processed by `inbox-process` first and its summary is the target (the vault has no inbox).
|
|
17
|
+
- Without a workspace, a single explicit source follows the same proposal and confirmation steps as a batch; invoke `/vault-extract` only after the user accepts its create proposal.
|
|
18
|
+
|
|
19
|
+
Raw recordings and unreviewed transcripts are not scanned by `/vault-sync`. In a workspace, only refined meeting notes under `work/meetings/YYYY/YYYY-MM/` are considered vault-worthy sources. Any transcript provider output must be processed through `meeting-notes` first. When the workspace or `meeting-notes` skill is unavailable, skip and report that workspace preprocessing step, ask for a reviewed meeting note or summary, and do not process the raw transcript.
|
|
20
|
+
|
|
21
|
+
## Process
|
|
22
|
+
|
|
23
|
+
### Step 1: Scan
|
|
24
|
+
|
|
25
|
+
2-source parallel scan:
|
|
26
|
+
|
|
27
|
+
#### 1A: Meeting Notes (highest priority)
|
|
28
|
+
```bash
|
|
29
|
+
# List all meeting files in current month (YYYY/YYYY-MM = today)
|
|
30
|
+
ls <workspace-root>/meetings/YYYY/YYYY-MM/
|
|
31
|
+
```
|
|
32
|
+
- Cross-reference vault notes source fields to find unprocessed meetings
|
|
33
|
+
- Grep vault `notes/` for `source:.*work/meetings/YYYY/YYYY-MM` to identify already-extracted
|
|
34
|
+
|
|
35
|
+
#### 1B: Git Diff (Work Root + Submodules)
|
|
36
|
+
```bash
|
|
37
|
+
# Work root: changes since last sync timestamp
|
|
38
|
+
cd <workspace-root>
|
|
39
|
+
LAST_SYNC=$(cat <vault.path>/ops/sessions/last-sync-timestamp)
|
|
40
|
+
# Convert YYYYMMDDHHMI to git date format
|
|
41
|
+
SINCE_DATE=$(echo $LAST_SYNC | sed 's/\(....\)\(..\)\(..\)\(..\)\(..\)/\1-\2-\3 \4:\5/')
|
|
42
|
+
|
|
43
|
+
# Root repo changes (exclude system/meetings/tasks — those have dedicated scanners)
|
|
44
|
+
git log --oneline --since="$SINCE_DATE" --name-only -- . \
|
|
45
|
+
':!.claude' ':!.obsidian' ':!meetings' ':!tasks' \
|
|
46
|
+
| grep -v '^\w\{7\} ' | grep -v '^$' | grep -v '\.json$' \
|
|
47
|
+
| grep -v 'uv.lock' | grep -v 'pyproject.toml' \
|
|
48
|
+
| sort -u
|
|
49
|
+
# The workspace system directory is dropped by the Step 1.5 filter rules
|
|
50
|
+
|
|
51
|
+
# Submodule changes: detect which submodules have new commits
|
|
52
|
+
git submodule status --recursive | grep '^+' | awk '{print $2}'
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**Submodule change detection**:
|
|
56
|
+
- `+` prefix in `git submodule status` = submodule HEAD differs from recorded commit
|
|
57
|
+
- For each changed submodule, check its recent commits:
|
|
58
|
+
```bash
|
|
59
|
+
cd <workspace-root>/$SUBMODULE
|
|
60
|
+
git log --oneline --since="$SINCE_DATE" --name-only -- . ':!.claude' \
|
|
61
|
+
| grep -v '^\w\{7\} ' | grep -v '^$' | sort -u
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**Work repo submodules**: 목록은 `.gitmodules`가 정본. `vault`는 스캔 대상이 아니라 목적지이고, 코드 저장소 서브모듈은 명시 요청 시에만 스캔한다. 그 외 work 트리는 일반 디렉토리이므로 루트 git diff 스캔이 덮는다.
|
|
65
|
+
|
|
66
|
+
### Step 1.5: Filter & Classify
|
|
67
|
+
|
|
68
|
+
**Filter rules** (reduce noise):
|
|
69
|
+
- Skip: the workspace system directory, `.json`, `uv.lock`, `pyproject.toml`, `*.css`, `*.js`, `*.html`
|
|
70
|
+
- Skip: draft versions if final exists (e.g., `drafts/YYMMDD-v2-*` if `final/YYMMDD-v4-*` exists)
|
|
71
|
+
- Skip: personal and code-repository submodules unless explicitly requested
|
|
72
|
+
- Include: `README.md`, `*-plan-*.md`, `*-report-*.md`, `*-summary-*.md`, `*-strategy-*.md`
|
|
73
|
+
- Include: any `.md` under the workspace's configured document roots
|
|
74
|
+
|
|
75
|
+
**Classify** per `references/vault-adapter.md` §Project Registry Pattern (scoring and fallback). A match attaches the project name and `vault_note` to the proposal; ambiguity marks it "project: TBD (user confirm)".
|
|
76
|
+
|
|
77
|
+
> **Entity resolution**: people/orgs/projects 해소는 워크스페이스 context-enrichment 규칙(`ssot.rules`)의 절차 사용 (fast cache → registry → vault MOC, 충돌 시 vault 우선).
|
|
78
|
+
|
|
79
|
+
**Deduplication** (multi-signal):
|
|
80
|
+
|
|
81
|
+
0. **`vmem_brief` first**: `vmem_brief(intent: "<source title> <key topics>", paths: ["<source work file>"], bytes: 1024)` ranks screened pointer lines by the intent words plus the source file's basename words (`paths` is a word hint, not a citation filter). Run it once per source before the checks below, then confirm a pointer with `vmem_search`; the checks below decide the verdict
|
|
82
|
+
1. **source field exact match**: `source: work/meetings/...` 경로 직접 일치
|
|
83
|
+
2. **Title similarity ≥70%**: fuzzy compare against vault note titles
|
|
84
|
+
3. **Recent update-section detection**: 대상 회의 날짜 헤더(`## Update (YYYY-MM-DD)` 또는 `## YYYY-MM-DD ...`)가 vault 노트에 이미 존재하면 "이미 반영됨"으로 판정
|
|
85
|
+
4. **Entity overlap** (보조): 회의 제목의 주요 인물·기관 키워드가 vault 노트 본문에 ≥3회 등장 시 후보
|
|
86
|
+
|
|
87
|
+
**판정 로직**:
|
|
88
|
+
- 1, 2, 3 중 **임의 하나 hit** → "already reflected — skip" 제안
|
|
89
|
+
- 1 miss + 2 hit (≥70%) → "update" 제안 (source field 갱신 포함)
|
|
90
|
+
- 모두 miss → "create" 제안
|
|
91
|
+
|
|
92
|
+
Standalone explicit-source precedence: if 1 or 3 hits, propose "already reflected — skip". If 1 and 3 miss but 2 hits, inspect the candidate and propose "update" only when related; show an unclear candidate to the user. This precedence applies only without a workspace.
|
|
93
|
+
|
|
94
|
+
### Step 2: Propose
|
|
95
|
+
|
|
96
|
+
Present candidates grouped by source and priority:
|
|
97
|
+
```
|
|
98
|
+
EXTRACTION PROPOSALS
|
|
99
|
+
====================
|
|
100
|
+
Scanned: meetings 9건, git-diff 5건, submodules 1건
|
|
101
|
+
|
|
102
|
+
─── MEETINGS (HIGH) ───
|
|
103
|
+
|
|
104
|
+
[1] MEETING: MM-DD partner meeting - example platform
|
|
105
|
+
-> Proposed: update [[example-partner-platform-mou]]
|
|
106
|
+
-> Domain: projects
|
|
107
|
+
|
|
108
|
+
─── GIT DIFF (MEDIUM-HIGH) ───
|
|
109
|
+
|
|
110
|
+
[2] DIFF: admin/example-unit/YYMMDD-org-restructuring.md (new file)
|
|
111
|
+
-> Proposed: update [[example-org-restructuring-decision]]
|
|
112
|
+
-> Domain: operations
|
|
113
|
+
|
|
114
|
+
[3] DIFF: projects/example-project/planning/YYMMDD-plan-masterplan.md (new file)
|
|
115
|
+
-> Proposed: update [[example-project-masterplan-idea]]
|
|
116
|
+
-> Domain: projects
|
|
117
|
+
|
|
118
|
+
─── SUBMODULE CHANGES ───
|
|
119
|
+
|
|
120
|
+
[4] SUBMODULE: sites/example-site (+1 commit, requested)
|
|
121
|
+
-> Changed: src/pages/
|
|
122
|
+
-> Proposed: update [[example-site-home]]
|
|
123
|
+
-> Domain: teaching
|
|
124
|
+
|
|
125
|
+
Accept: [a]ll, [1-4] select, [s]kip, [q]uit
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### Step 3: Confirm
|
|
129
|
+
- User selects which proposals to execute
|
|
130
|
+
- Follow `/vault-extract` §Extraction Fidelity and Concurrent Writers on every extraction; its one-writer rule's condition, stated in that rule, decides when it applies
|
|
131
|
+
- For each confirmed proposal:
|
|
132
|
+
1. Read the source document fully
|
|
133
|
+
2. **create** proposals: extract insights per `/vault-extract` methodology → create vault note(s) → update relevant MOCs
|
|
134
|
+
3. **update** proposals: hand off to the `/vault-update` procedure (MCP `vmem_patch`/`vmem_append`/`vmem_set_frontmatter` with the original insight preserved, `## Update YYYY-MM-DD` section, `/vault-lint note=` afterwards when the CLI is available) — this skill does not carry its own update path
|
|
135
|
+
4. Show created/updated note for review
|
|
136
|
+
|
|
137
|
+
### Step 3.5: R4 Sibling Merge (Method Evidence 자동 갱신)
|
|
138
|
+
|
|
139
|
+
이번 라운드에서 **R4 sibling merge**(≥2 meetings → 1 노트 merge)가 1건 이상 실행됐으면, Step 4 전에 `references/r4-method-evidence.md`를 읽고 method 노트의 evidence 테이블을 갱신한다.
|
|
140
|
+
|
|
141
|
+
**Skip 조건**:
|
|
142
|
+
- R4 merge 0건인 세션 → Step 3.5 skip
|
|
143
|
+
- User가 /vault-sync --skip-method-update 플래그 사용 시
|
|
144
|
+
|
|
145
|
+
### Step 4: Record
|
|
146
|
+
- Update last-sync timestamp in `ops/sessions/last-sync-timestamp` (plain file, fs write)
|
|
147
|
+
- Log sync results in `ops/sessions/YYYYMMDD-sync.md` with `vmem_report(path: "ops/sessions/YYYYMMDD-sync.md", body)` (expect: vmem refuses secret-looking text and an unsafe path)
|
|
148
|
+
- Promote vault-relevant `TASK` events from the work-local `.maru/tasks-log.md`
|
|
149
|
+
to `vault/log` with `vmem_log_append(type: "TASK", ...)` (task-management does not write the
|
|
150
|
+
vault directly)
|
|
151
|
+
- **Graph freshness**: run vault-lint L11 (graph staleness). If `vault-graph.json`
|
|
152
|
+
is > 7 days stale, propose `/vault-graph build`. Suggest only — do not auto-build.
|
|
153
|
+
|
|
154
|
+
## Scope Details
|
|
155
|
+
|
|
156
|
+
### /vault-sync meetings
|
|
157
|
+
- Scan work/meetings/YYYY/ (current year) for notes not yet in vault
|
|
158
|
+
- Cross-reference vault notes source fields
|
|
159
|
+
- Extract: decisions, insights, relationship updates
|
|
160
|
+
|
|
161
|
+
### /vault-sync projects
|
|
162
|
+
- Git diff on work root + project submodules
|
|
163
|
+
- Scan work/projects/ README and key doc changes
|
|
164
|
+
- Compare with existing vault project notes
|
|
165
|
+
- Propose updates to existing notes or new notes
|
|
166
|
+
|
|
167
|
+
### /vault-sync diff
|
|
168
|
+
- Git diff only (skip meeting scanners)
|
|
169
|
+
- Work root + all submodules
|
|
170
|
+
- Useful for catching project doc changes between meeting-heavy days
|
|
171
|
+
|
|
172
|
+
### /vault-sync targets <path>...
|
|
173
|
+
- Skip Step 1. Enumerate eligible sources under the given source paths (`.md` with frontmatter, or summary output); at most 20 per run (collector's-fallacy guard: split larger batches)
|
|
174
|
+
- Step 1.5 classification and deduplication run once for the whole batch, and the classification is passed to each extraction (no registry reload per item)
|
|
175
|
+
- The named targets are the user's choice of sources: Step 2 shows the proposal list once and one accept covers the batch (per-item select still works)
|
|
176
|
+
- Step 3 runs the `/vault-extract` method per accepted create proposal and hands accepted update proposals to `/vault-update` as in other scopes, then `/vault-connect` on the notes it created. Check quality once after the batch with one `vmem_lint` call (or the CLI `vmem lint <vault> --note <path>` per note when the CLI is available)
|
|
177
|
+
- Stop on a refusal or a persisted partial write (see `references/vault-adapter.md` §Write results); continue past warnings
|
|
178
|
+
- Output adds: sources skipped by vault-extract preconditions, per-note lint error/warning counts
|
|
179
|
+
- Step 4 writes the session record but does not move `ops/sessions/last-sync-timestamp`: a targets run covers only the named sources, not every change since the last sync
|
|
180
|
+
|
|
181
|
+
### /vault-sync full
|
|
182
|
+
- All of the above in priority order: meetings → git diff → submodules
|
|
183
|
+
- Limit: max 10 proposals per run (avoid overwhelm)
|
|
184
|
+
- Raw recordings and transcripts must be refined into `work/meetings/` first
|
|
185
|
+
|
|
186
|
+
## Quality Gates
|
|
187
|
+
- Same as /vault-extract quality gates
|
|
188
|
+
- Additional: deduplication check before creation
|
|
189
|
+
- Confirmation required for every note creation (in `targets`, the one batch accept is that confirmation)
|
|
190
|
+
|
|
191
|
+
## Output
|
|
192
|
+
- Summary of scan results (per source: meetings, diff, submodules)
|
|
193
|
+
- Numbered proposals with accept/skip interface
|
|
194
|
+
- After execution: list of created/updated notes
|
|
195
|
+
- Updated sync timestamp
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# R4 Sibling Merge: Method Evidence 갱신
|
|
2
|
+
|
|
3
|
+
이번 세션에서 **R4 sibling merge**가 1건 이상 실행된 경우 (≥2 meetings → 1 노트 merge), 워크스페이스가 지정한 R4 method 노트(이하 `<r4-method-note>`; 워크스페이스 설정에 없으면 사용자에게 묻는다)의 evidence 테이블을 자동 갱신한다.
|
|
4
|
+
|
|
5
|
+
**절차**:
|
|
6
|
+
1. 이번 /vault-sync 라운드에서 수행한 R4 merge 노트 목록 수집 (target note + merged sessions count)
|
|
7
|
+
2. `vmem_read(path: '<r4-method-note>')` 호출 (sha256 보관)
|
|
8
|
+
3. `## 실증 사례 (3건, YYYY-MM-DD 기준)` 테이블에서 해당 merged 노트 행 찾기
|
|
9
|
+
4. **누적 N 증가**: `N = 기존 N + 이번 라운드 병합 수`
|
|
10
|
+
5. **날짜 분포 append**: `기존 분포 + MM-DD(N추가)` 형태로 append
|
|
11
|
+
6. 표를 한 번의 `vmem_patch`로 갱신한다. 표 전체를 통째로 바꾸면 `vmem_patch(path, oldString: <기존 표 전체>, newString: <갱신 표 전체>, expectedSha: <2단계 sha256>)`, 여러 행·칸만 고칠 때는 `vmem_patch(path, edits: [{oldString, newString}, ...], expectedSha)`로 한 호출에 묶는다 (`edits[]`는 1..32쌍, 원문에서 각각 한 번만 매치해야 하고, 전부 아니면 전무로 적용되며 로그도 1줄만 남는다). 나눠 고쳐야 하면 매 patch 뒤 `vmem_read`로 새 sha256을 받아 다음 patch에 쓴다. expect: vmem refuses a stale `expectedSha` (V09), an `edits[]` pair that matches nowhere or twice, and an overlapping pair
|
|
12
|
+
7. 신규 merged 노트(케이스 추가)인 경우 **새 행** 추가
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vault-update
|
|
3
|
+
trigger: /vault-update
|
|
4
|
+
description: Refresh an outdated note with new context while preserving core insight (via vmem)
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# /vault-update [note]
|
|
8
|
+
|
|
9
|
+
> Before the first vmem call, read `references/vault-adapter.md` §Runtime Discovery and select and bind the vmem vault id; pass it as `vault` on every vmem tool call and as the `<vault>` argument of every `vmem` CLI command.
|
|
10
|
+
|
|
11
|
+
Update a note with new information while preserving original meaning. This is the single-note leaf; batch discovery of notes that need updating is `/vault-sync` (its "update" proposals run this procedure). Every update follows `/vault-extract` §Extraction Fidelity and Concurrent Writers, and step 3 applies its rules to a revision.
|
|
12
|
+
|
|
13
|
+
## Input
|
|
14
|
+
- note: filename or path in `notes/`
|
|
15
|
+
|
|
16
|
+
## Process
|
|
17
|
+
|
|
18
|
+
1. Read target note via `vmem_read` (keep its `sha256` for `expectedSha`)
|
|
19
|
+
2. Identify what's changed (new context, superseded info, additional evidence)
|
|
20
|
+
3. Draft the update:
|
|
21
|
+
- preserve core insight
|
|
22
|
+
- add new content in an explicit section (e.g., `## Update YYYY-MM-DD`) OR inline-revise with preservation: a revised value that came from a source keeps the earlier value and its source beside it, e.g. `amount 3,000,000 (source: work/<contract>.md); revised 4,000,000 (source: work/<minutes>.md)`
|
|
23
|
+
4. Apply via vmem:
|
|
24
|
+
- minor edit → `vmem_patch(path, oldString, newString, expectedSha)`
|
|
25
|
+
- new section → `vmem_append(path, section: "Update YYYY-MM-DD", markdown)`
|
|
26
|
+
- major rewrite → there is no overwrite tool: patch section by section, or create a replacement note with `vmem_create` and retire the old one with `vmem_supersede(old, next)`
|
|
27
|
+
- the new information duplicates another note → do not update into a copy: offer `vmem_merge(keep, absorb)` at the approval gate, preview first and confirm with the fingerprint; it unions source and topics and repoints inbound links itself
|
|
28
|
+
- frontmatter change → `vmem_set_frontmatter(path, set, unset, expectedSha)`
|
|
29
|
+
- expect: vmem refuses a stale `expectedSha`, an invalid frontmatter value, a new unresolved wiki link, an edit inside `## Topics`, and a `vmem_merge` of different types, a person or MOC note, or an oversized result
|
|
30
|
+
5. Check connected notes (via `vmem_links(path)` and `vmem_brief(intent: "<title> <description>", bytes: 1024)`); propose cascading updates if needed
|
|
31
|
+
6. Record update in note body (timestamp or changelog line)
|
|
32
|
+
7. Run `/vault-lint note=<path>` on the updated note; `--note` is CLI-only, so an MCP-only run finishes with one vault-wide `vmem_lint` instead
|
|
33
|
+
8. vmem logs every write with a default `EXTRACT` line; when wiki-links changed, pass `log: {type: "CONNECT", ...}` on the write that changed them (see §Log Append)
|
|
34
|
+
|
|
35
|
+
## Vault Access
|
|
36
|
+
|
|
37
|
+
Use vmem through the transport in the adapter. No filesystem Read/Write/Edit on vault paths. Use:
|
|
38
|
+
|
|
39
|
+
| Operation | vmem tool |
|
|
40
|
+
|-----------|---------|
|
|
41
|
+
| Read | `vmem_read` |
|
|
42
|
+
| Full rewrite | section `vmem_patch` calls, or `vmem_create` + `vmem_supersede` |
|
|
43
|
+
| Append | `vmem_append` |
|
|
44
|
+
| Targeted edit | `vmem_patch` |
|
|
45
|
+
| Frontmatter and tags | `vmem_set_frontmatter` |
|
|
46
|
+
| Search for impact | `vmem_links`, `vmem_search` |
|
|
47
|
+
|
|
48
|
+
## Quality Gates
|
|
49
|
+
|
|
50
|
+
- Original insight must be preserved OR explicitly superseded with `status: superseded` frontmatter + link to replacement note
|
|
51
|
+
- All existing wiki-links must remain valid
|
|
52
|
+
- New wiki-links added where relevant
|
|
53
|
+
- Changelog/timestamp line appended to body when content changes materially
|
|
54
|
+
|
|
55
|
+
## Log Append
|
|
56
|
+
|
|
57
|
+
Each vmem write records exactly one line: its default `EXTRACT` event, or the event the call passes in `log`. Nothing suppresses it, so a body-only edit is logged too and is never silent. When the edit adds or removes a wiki link or MOC membership, pass `log: {type: "CONNECT", project, source: "notes/<note>.md", dest, note: "updated: <summary>"}` on the write that changed them:
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
YYYY-MM-DD HH:MM CONNECT <project> notes/<note>.md — updated: <summary>
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Output
|
|
64
|
+
|
|
65
|
+
- Summary of changes made
|
|
66
|
+
- Connected notes reviewed (and any cascading proposals)
|
|
67
|
+
- note-level `/vault-lint` result
|
|
68
|
+
- log append status (if applicable)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: vmem-status
|
|
3
|
+
description: Use when asked which vmem version is installed, whether vmem is up to date, or whether the vmem install and its vault registry are healthy (not note content; that is vault-stats). Reports the running vmem build, installed skill version, other installs on PATH, registered vaults and doctor findings, read-only.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# vmem-status
|
|
7
|
+
|
|
8
|
+
Answer "what vmem runs here and is it healthy" in one report. Every step is read-only: give repairs as commands for the person to run.
|
|
9
|
+
|
|
10
|
+
## Process
|
|
11
|
+
|
|
12
|
+
When only MCP is available, call `vmem_status` for its registered vaults and health; use MCP server version metadata if the host exposes it. Compare that version with the local marker when both are available. Report the CLI build, PATH, doctor, recover and other CLI-only checks as unavailable, not healthy or failed. Do not infer fields absent from the MCP response. When only the CLI is available, run steps 1–5 and skip the MCP comparison.
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
1. **Build**: run `vmem --version`. Read `version` from `.vmem-skill.json` in this installed skill directory and compare it with the running version. Report a mismatch as stale skills and suggest `vmem setup <host> --apply` for the actual host. If the marker is missing or unreadable, report the skill version as unknown.
|
|
16
|
+
2. **Other installs**: list every `vmem` on PATH (`which -a vmem`, `where vmem` on Windows) and run `--version` on each distinct resolved file. When versions differ, the lower one is stale. A stale install that runs is replaced by fixing PATH order or removing it; a stale shadowed install runs whenever PATH order changes, so remove it.
|
|
17
|
+
3. **Registry**: run `vmem status --json`. Take `version`, `home`, `source`, `healthy`, and per vault `id`, `kind`, `write`, `pii`, `healthy`, `path`.
|
|
18
|
+
4. **Doctor**: run `vmem doctor --json`. Its top-level `healthy` and exit code (1 means unhealthy, a finding to report, not a failure of this skill) are the verdict. Report each vault with `healthy: false` and its `issue`, each `vaults[].checks.<name>` with `ok: false` and its `issue`, each `specs[]` entry with `healthy: false` and its `issue`, and each vault's `tidy` (pending migration) as a warning.
|
|
19
|
+
5. **Leftovers**: run `vmem recover --json` without `--confirm`; it only previews. Report `lock.state` and any `temporaryFiles`. Exit 1 with `blocked` is a finding: a `live` lock means a writer is running, so wait and rerun; an `unknown` owner (unreadable, or another host's lock) means the person confirms no writer runs on any host, then removes `lock.path` by hand.
|
|
20
|
+
6. **MCP**: when the vmem MCP tools are available, call `vmem_status`. If step 3 also ran, a vault list that differs from step 3 means the MCP server started before the last registry change (restart the host session) or runs another build or home; report which fits. A `vaults remove` does not show as a mismatch, so after one the server needs a restart either way.
|
|
21
|
+
|
|
22
|
+
A matching skill marker and running version proves only local consistency, not that either is the latest release. When asked whether vmem is up to date, compare the running version with a verifiable current release from the package registry or release source when available; identify that source. If it cannot be checked, report latest-release status as unknown.
|
|
23
|
+
|
|
24
|
+
## Output
|
|
25
|
+
|
|
26
|
+
- One line: running version, installed skill version and local match verdict; separately report latest-release status as current, outdated, or unknown with its evidence.
|
|
27
|
+
- Other installs with versions, only when step 2 found any.
|
|
28
|
+
- Vaults table: id, kind, write, pii, health, path.
|
|
29
|
+
- Doctor failures and tidy warnings from step 4; "healthy" only when doctor's `healthy` is true.
|
|
30
|
+
- At most one next action with its command: repair stale skills with `vmem setup <host> --apply`, the repair a doctor `issue` names, `vmem recover --confirm` when step 5 is not `blocked` and shows a `stale` lock or `temporaryFiles`, rerunning `vmem recover --json` after a live writer finishes, or removing the file at `lock.path` once no writer runs, `vmem tidy <vault> --all` (preview) for pending migration, or removing a stale install with the package manager that owns it.
|
package/src/amem/host-api.ts
CHANGED
|
@@ -16,8 +16,12 @@ export function installedAmemVersion(entry: string): string {
|
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
18
|
export const amemVersion = () => installedAmemVersion(createRequire(import.meta.url).resolve("@staix/agent-mem/platform"));
|
|
19
|
+
export class HostApiVersionError extends Error {
|
|
20
|
+
readonly code = "VMEM_HOST_API_INCOMPATIBLE";
|
|
21
|
+
}
|
|
22
|
+
|
|
19
23
|
export function checkHostApi(api: { HOST_API_MIN?: unknown; HOST_API_VERSION?: unknown }, version: string): void {
|
|
20
24
|
const min = api.HOST_API_MIN, max = api.HOST_API_VERSION;
|
|
21
25
|
if (Number.isSafeInteger(min) && Number.isSafeInteger(max) && (min as number) >= 1 && (min as number) <= 1 && (max as number) >= 1) return;
|
|
22
|
-
throw new
|
|
26
|
+
throw new HostApiVersionError(`agent-mem ${version}: host API ${String(min ?? "missing")}..${String(max ?? "missing")} is incompatible with vmem host API 1; update @staix/agent-mem or @staix/vault-mem to compatible versions`);
|
|
23
27
|
}
|
package/src/analysis-input.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readEnrichmentStore } from "./enrichment-store.ts";
|
|
1
3
|
import { localDate } from "./local-date.ts";
|
|
2
4
|
import { MAX_REPORT_BYTES } from "./write-validation.ts";
|
|
3
5
|
import { parseFrontmatter } from "./frontmatter.ts";
|
|
@@ -92,6 +94,19 @@ export function analysisInput(home: string, id: string, options: { today?: strin
|
|
|
92
94
|
if(found.length)warnings[note.path]=found;
|
|
93
95
|
}catch{ /* Invalid frontmatter remains visible to L02; do not infer missing source paths. */ }
|
|
94
96
|
if(Object.keys(warnings).length)snapshot.sourceWarnings=warnings;
|
|
97
|
+
if (vault.graph?.resolution !== undefined) snapshot.graphResolution = vault.graph.resolution;
|
|
98
|
+
if (options.hints && vault.enrichment?.enabled) {
|
|
99
|
+
const store = readEnrichmentStore(home, vault, config.vaults, config.denyPaths ?? []);
|
|
100
|
+
const embeddings = new Set(store.records.filter(r => r.kind === "embedding").map(r => JSON.stringify([r.path, r.contentHash])));
|
|
101
|
+
const paths = new Set(store.records.filter(r => r.kind === "embedding").map(r => r.path));
|
|
102
|
+
const enrichmentWarnings: Record<string, string[]> = Object.create(null);
|
|
103
|
+
for (const note of snapshot.notes) {
|
|
104
|
+
const path = `notes/${note.path.replace(/^notes\//, "")}`;
|
|
105
|
+
const hash = createHash("sha256").update(note.source).digest("hex");
|
|
106
|
+
if (!embeddings.has(JSON.stringify([path, hash]))) enrichmentWarnings[note.path] = [`embedding ${paths.has(path) ? "stale" : "missing"}; run enrichment for the current note`];
|
|
107
|
+
}
|
|
108
|
+
snapshot.enrichmentWarnings = enrichmentWarnings;
|
|
109
|
+
}
|
|
95
110
|
// Evidence drift is a read/lint finding: status and reason only, never the quote or source text.
|
|
96
111
|
const drift:Record<string,string[]>=Object.create(null),reads:EvidenceReads=new Map();
|
|
97
112
|
for(const note of snapshot.notes)try{
|
package/src/analysis-types.ts
CHANGED
|
@@ -3,6 +3,8 @@ import type { TitleSuggestion } from "./links.ts";
|
|
|
3
3
|
export interface AnalysisSnapshot {
|
|
4
4
|
/** Effective selected-vault domain set; standalone snapshots default to the built-ins. */
|
|
5
5
|
domains?: string[];
|
|
6
|
+
graphResolution?: number;
|
|
7
|
+
enrichmentWarnings?: Record<string, string[]>;
|
|
6
8
|
notes: { path: string; source: string }[];
|
|
7
9
|
today: string;
|
|
8
10
|
logPath: string;
|
|
@@ -27,7 +29,7 @@ export interface AnalysisSnapshot {
|
|
|
27
29
|
*/
|
|
28
30
|
linkHintBound?: { cap: number; attempted: readonly string[]; skipped: number };
|
|
29
31
|
}
|
|
30
|
-
export type LintCode = "L01" | "L02" | "L03" | "L09" | "L10" | "L11" | "L12" | "L13" | "L14" | "L15" | "L16" | "L17";
|
|
32
|
+
export type LintCode = "L01" | "L02" | "L03" | "L09" | "L10" | "L11" | "L12" | "L13" | "L14" | "L15" | "L16" | "L17" | "L18" | "L19";
|
|
31
33
|
export interface LintReport {
|
|
32
34
|
findings: Record<LintCode, string[]>;
|
|
33
35
|
errors: number;
|
package/src/assertion-policy.ts
CHANGED
|
@@ -8,10 +8,11 @@ import { screenContent } from "./write-validation.ts";
|
|
|
8
8
|
import type { AssertionItem } from "./assertions.ts";
|
|
9
9
|
|
|
10
10
|
export type AssertionValue = string | { withheld: "secret" | "pii_policy" };
|
|
11
|
-
export type ScreenedAssertion = Omit<AssertionItem, "value" | "evidence" | "source"> & {
|
|
11
|
+
export type ScreenedAssertion = Omit<AssertionItem, "value" | "evidence" | "source" | "origin"> & {
|
|
12
12
|
value?: AssertionValue;
|
|
13
13
|
evidence?: Record<string, unknown>[];
|
|
14
14
|
source?: (string | { withheld: true })[];
|
|
15
|
+
origin?: AssertionItem["origin"] | { withheld: true };
|
|
15
16
|
availability?: "unavailable";
|
|
16
17
|
};
|
|
17
18
|
|
|
@@ -31,8 +32,9 @@ function deniedSource(source: string, vault: VaultSpec, config: VmemConfig): boo
|
|
|
31
32
|
|
|
32
33
|
/** Screen every field on every read. A denied evidence entry reveals neither its source, quote nor hashes. */
|
|
33
34
|
export function screenAssertion(item: AssertionItem, vault: VaultSpec, config: VmemConfig, reads: EvidenceReads, budget: EvidenceReadBudget): ScreenedAssertion {
|
|
34
|
-
const { value, evidence, source, ...safe } = item;
|
|
35
|
+
const { value, evidence, source, origin, ...safe } = item;
|
|
35
36
|
const out: ScreenedAssertion = { ...safe };
|
|
37
|
+
if (origin !== undefined) out.origin = !origin || typeof origin !== "object" || typeof origin.path !== "string" || !/^notes\/[^/\\]+\.md$/.test(origin.path) || isDenied(origin.path, config.denyPaths ?? []) || isDenied(canonicalPath(resolve(vault.path, origin.path)), config.denyPaths ?? []) || withheld(JSON.stringify(origin), vault, config) ? { withheld: true } : origin;
|
|
36
38
|
if (item.purged) { out.availability = "unavailable"; out.evidence = [{ status: "unavailable" }]; return out; }
|
|
37
39
|
if (typeof value === "string") {
|
|
38
40
|
const reason = withheld(value, vault, config);
|
package/src/assertions.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* `evaluateAssertions` is the pure evaluation the read surface wraps, and `appendAssertions` is the write contract.
|
|
7
7
|
* Nothing here writes a note, an `updated` stamp or a log line unless the caller supplies a log event.
|
|
8
8
|
*/
|
|
9
|
-
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
10
10
|
import { closeSync, constants, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, realpathSync, renameSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
|
|
11
11
|
import { hostname } from "node:os";
|
|
12
12
|
import { join, resolve } from "node:path";
|
|
@@ -19,6 +19,7 @@ import { canonicalPath, isDenied } from "./platform.ts";
|
|
|
19
19
|
import { loadRegistry, syncDirectory } from "./registry.ts";
|
|
20
20
|
import { sourceReferences, sourceWorkspaceRoot } from "./source.ts";
|
|
21
21
|
import { appendLog, checkLogEvent } from "./vault-log.ts";
|
|
22
|
+
import { MAX_NOTE_BYTES } from "./vault-index.ts";
|
|
22
23
|
import { screenContent, screenMetadata } from "./write-validation.ts";
|
|
23
24
|
import type { WriteIssue } from "./write-types.ts";
|
|
24
25
|
import { shellWord } from "./text-output.ts";
|
|
@@ -73,7 +74,7 @@ export type Answer = "yes" | "no" | "unknown";
|
|
|
73
74
|
export interface AssertionItem {
|
|
74
75
|
id: string; rev: number; op: "assert" | "revise" | "retract"; subject: string; relation: string; hash: string;
|
|
75
76
|
value?: string; kind?: "state" | "event"; from?: string; to?: string; held_on?: string; on?: string; reason?: string;
|
|
76
|
-
evidence?: unknown[]; source?: string[];
|
|
77
|
+
evidence?: unknown[]; source?: string[]; origin?: EnrichmentOrigin & { status: "unverified" };
|
|
77
78
|
answer?: Answer; recordedAt: string; effectiveRecordedAt?: string; clockInverted?: true; replacedAt?: string | null;
|
|
78
79
|
revisionConflict?: true; heads?: string[]; purged?: true;
|
|
79
80
|
segment?: string; seq?: number;
|
|
@@ -384,7 +385,7 @@ function item(state: AssertionState, kept: Kept, t: number | undefined): Asserti
|
|
|
384
385
|
const { entry } = kept, payload = entry.payload ?? {};
|
|
385
386
|
const out: AssertionItem = { id: state.id, rev: entry.op === "assert" ? 1 : entry.purged ? kept.depth + 1 : Number(payload.rev), op: entry.op as AssertionItem["op"], subject: entry.purged ? "" : state.subject, relation: entry.purged ? "" : state.relation, hash: entry.hash, recordedAt: entry.recorded_at };
|
|
386
387
|
if (entry.purged) { out.purged = true; out.segment = entry.seg; out.seq = entry.seq; }
|
|
387
|
-
for (const key of ["value", "kind", "from", "to", "held_on", "on", "reason", "evidence", "source"] as const) if (payload[key] !== undefined) (out as unknown as Record<string, unknown>)[key] = payload[key];
|
|
388
|
+
for (const key of ["value", "kind", "from", "to", "held_on", "on", "reason", "evidence", "source", "origin"] as const) if (payload[key] !== undefined) (out as unknown as Record<string, unknown>)[key] = payload[key];
|
|
388
389
|
if (kept.inverted) { out.effectiveRecordedAt = kept.effective; out.clockInverted = true; }
|
|
389
390
|
if (t !== undefined && entry.op !== "retract" && !entry.purged) out.answer = answerOn(payload, t);
|
|
390
391
|
return out;
|
|
@@ -463,6 +464,8 @@ export type AssertOp =
|
|
|
463
464
|
| { op: "assert"; subject: string; relation: string; value: string; kind: "state" | "event"; from?: string; to?: string; held_on?: string; on?: string; evidence?: EvidenceEntry[]; source?: string[] }
|
|
464
465
|
| { op: "revise"; id: string; expected_heads: string[]; value: string; kind: "state" | "event"; from?: string; to?: string; held_on?: string; on?: string; evidence?: EvidenceEntry[]; source?: string[] }
|
|
465
466
|
| { op: "retract"; id: string; expected_heads: string[]; reason: typeof REASONS[number] };
|
|
467
|
+
export interface EnrichmentOrigin { path: string; sha256: string; producer: { skill: string; version: string; model: string }; createdAt: string; intakeId?: string }
|
|
468
|
+
export interface AssertOptions { env?: NodeJS.ProcessEnv; now?: Date; origin?: EnrichmentOrigin }
|
|
466
469
|
export interface AssertRequest { vault: string; ops: unknown; channel?: "cli" | "mcp"; dryRun?: boolean; log?: LogEvent }
|
|
467
470
|
export interface AssertReceipt {
|
|
468
471
|
ok: boolean; applied: boolean; dryRun: boolean;
|
|
@@ -564,7 +567,7 @@ function context(home: string, request: { vault: string; channel?: "cli" | "mcp"
|
|
|
564
567
|
return { vault, config, root, channel };
|
|
565
568
|
}
|
|
566
569
|
/** Validate a batch against the journal as read (shapes, bounds, temporal rules, evidence, screening, heads). */
|
|
567
|
-
function plan(ctx: Context, ops: unknown, journal: VerifiedJournal): Planned[] {
|
|
570
|
+
function plan(ctx: Context, ops: unknown, journal: VerifiedJournal, origin?: EnrichmentOrigin): Planned[] {
|
|
568
571
|
if (!ops || !Array.isArray(ops) || ops.length < 1 || ops.length > MAX_BATCH_OPS) refuse("V01", `ops must be a list of 1..${MAX_BATCH_OPS} operations; split larger batches`);
|
|
569
572
|
if (bytes(canonical(ops)) > MAX_BATCH_BYTES) refuse("V09", `the canonical batch exceeds ${MAX_BATCH_BYTES} bytes; split it into smaller batches`);
|
|
570
573
|
const resolved = resolveEntries(journal), { assertions, subjects } = states(resolved.kept.values());
|
|
@@ -614,6 +617,7 @@ function plan(ctx: Context, ops: unknown, journal: VerifiedJournal): Planned[] {
|
|
|
614
617
|
entry = { op: "revise", id: op.id, target: op.id, parents: heads, payload: { id: op.id, rev, value: held, ...world, evidence: backing.evidence, ...(backing.source ? { source: backing.source } : {}) } };
|
|
615
618
|
}
|
|
616
619
|
}
|
|
620
|
+
if (origin && (entry.op === "assert" || entry.op === "revise")) entry.payload.origin = { ...origin, status: "unverified" };
|
|
617
621
|
const text = canonical(entry.payload);
|
|
618
622
|
if (bytes(text) > MAX_PAYLOAD_BYTES) refuse("V09", `${at}: payload exceeds ${MAX_PAYLOAD_BYTES} bytes as canonical JSON; shorten quotes or split evidence`);
|
|
619
623
|
const screened = [...screenContent(text, ctx.vault, ctx.config, "notes"), ...screenMetadata(entry.payload, { vault: ctx.vault, config: ctx.config, piiSurface: "notes" }, at)]
|
|
@@ -701,14 +705,43 @@ function release(lock: { fd: number; file: string; ino: number; dev: number }, i
|
|
|
701
705
|
} catch { issues.push({ code: "CLEANUP", severity: "warning", message: "assertions lock retained; inspect before removing it manually" }); }
|
|
702
706
|
}
|
|
703
707
|
|
|
708
|
+
/** Validate untrusted producer claims independently of the public request schema. */
|
|
709
|
+
function validateOrigin(value: unknown): EnrichmentOrigin {
|
|
710
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) refuse("V01", "origin must contain path, sha256, producer and createdAt");
|
|
711
|
+
const origin = value as Record<string, unknown>, producer = origin.producer;
|
|
712
|
+
if ((Object.keys(origin).some(key => !["createdAt", "path", "producer", "sha256", "intakeId"].includes(key)) || (origin.intakeId !== undefined && (typeof origin.intakeId !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(origin.intakeId)))) || typeof origin.path !== "string" || !/^notes\/[^/\\]+\.md$/.test(origin.path) || /\p{Cc}/u.test(origin.path) || !origin.path.isWellFormed() || typeof origin.sha256 !== "string" || !HEX64.test(origin.sha256) || !(typeof origin.createdAt === "string" && !Number.isNaN(Date.parse(origin.createdAt)) && new Date(origin.createdAt).toISOString() === origin.createdAt) || !producer || typeof producer !== "object" || Array.isArray(producer) || Object.keys(producer).sort().join(",") !== "model,skill,version") refuse("V01", "origin requires a flat note path, lowercase SHA-256, canonical ISO createdAt and producer skill, version and model");
|
|
713
|
+
for (const value of Object.values(producer as Record<string, unknown>)) if (typeof value !== "string" || !value.trim() || bytes(value) > 200 || /\p{Cc}/u.test(value) || !value.isWellFormed()) refuse("V01", "origin producer fields must be nonempty well-formed text of at most 200 bytes without control characters");
|
|
714
|
+
return origin as unknown as EnrichmentOrigin;
|
|
715
|
+
}
|
|
716
|
+
/** Recheck exact bytes of a plain note under the journal lock immediately before publication. */
|
|
717
|
+
function verifyOrigin(ctx: Context, origin: EnrichmentOrigin): void {
|
|
718
|
+
const file = join(ctx.root, origin.path), notes = join(ctx.root, "notes");
|
|
719
|
+
if (isDenied(origin.path, ctx.config.denyPaths ?? []) || isDenied(canonicalPath(file), ctx.config.denyPaths ?? [])) refuse("V06", "origin note is denied by current policy; choose an allowed source");
|
|
720
|
+
let fd: number | undefined;
|
|
721
|
+
try {
|
|
722
|
+
if (realpathSync(notes) !== notes) refuse("V04", "origin notes directory must be a plain directory; inspect the vault path");
|
|
723
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
724
|
+
const before = fstatSync(fd, { bigint: true });
|
|
725
|
+
if (!before.isFile() || before.size > BigInt(MAX_NOTE_BYTES)) refuse("V09", "origin note must be a bounded regular file; inspect the source");
|
|
726
|
+
const data = Buffer.alloc(Number(before.size) + 1); let length = 0;
|
|
727
|
+
while (length < data.length) { const n = readSync(fd, data, length, data.length - length, null); if (!n) break; length += n; }
|
|
728
|
+
const after = fstatSync(fd, { bigint: true }), named = lstatSync(file, { bigint: true });
|
|
729
|
+
if (named.isSymbolicLink() || named.dev !== after.dev || named.ino !== after.ino || length !== Number(before.size) || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) refuse("CONCURRENT", "origin note changed during verification; reread it and regenerate the result");
|
|
730
|
+
if (createHash("sha256").update(data.subarray(0, length)).digest("hex") !== origin.sha256) refuse("STALE_ORIGIN", "origin source content hash is stale; reread the note and regenerate the result before retrying");
|
|
731
|
+
} catch (caught) {
|
|
732
|
+
if (caught instanceof Refused) throw caught;
|
|
733
|
+
refuse("V04", "origin note cannot be read as a plain file; inspect its path and retry");
|
|
734
|
+
} finally { if (fd !== undefined) closeSync(fd); }
|
|
735
|
+
}
|
|
736
|
+
|
|
704
737
|
/**
|
|
705
738
|
* Validate and append one batch (design: Write contract). All-or-nothing: any error refuses the whole batch before
|
|
706
739
|
* any byte is written. A dry run validates against the journal as read, without lock, append or `recordedAt`.
|
|
707
740
|
*/
|
|
708
|
-
export function appendAssertions(home: string, request: AssertRequest, options:
|
|
741
|
+
export function appendAssertions(home: string, request: AssertRequest, options: AssertOptions = {}): AssertReceipt {
|
|
709
742
|
return appendAssertionsInternal(home, request, options);
|
|
710
743
|
}
|
|
711
|
-
function appendAssertionsInternal(home: string, request: AssertRequest, options:
|
|
744
|
+
function appendAssertionsInternal(home: string, request: AssertRequest, options: AssertOptions, heldRoot?: string): AssertReceipt {
|
|
712
745
|
const env = options.env ?? process.env;
|
|
713
746
|
const receipt: AssertReceipt = { ok: false, applied: false, dryRun: request?.dryRun === true, segment: null, entries: [], recovery: [], issues: [], indexUpdated: false };
|
|
714
747
|
let lock: ReturnType<typeof acquire> | undefined;
|
|
@@ -721,16 +754,22 @@ function appendAssertionsInternal(home: string, request: AssertRequest, options:
|
|
|
721
754
|
const logIssues = checkLogEvent(home, { vault: request.vault, event: request.log, channel: ctx.channel }, env);
|
|
722
755
|
if (logIssues.length) throw new Refused(logIssues.map(found => ({ ...found, message: `log event refused, nothing written: ${found.message}; fix the event fields (rules as for log append) or omit it` })));
|
|
723
756
|
}
|
|
757
|
+
const origin = options.origin === undefined ? undefined : validateOrigin(options.origin);
|
|
758
|
+
if (origin) {
|
|
759
|
+
const screened = [...screenContent(canonical(origin), ctx.vault, ctx.config, "notes"), ...screenMetadata({ ...origin }, { vault: ctx.vault, config: ctx.config, piiSurface: "notes" }, "origin")].filter(issue => issue.severity === "error");
|
|
760
|
+
if (screened.length) throw new Refused(screened);
|
|
761
|
+
}
|
|
724
762
|
if (receipt.dryRun) {
|
|
763
|
+
if (origin) verifyOrigin(ctx, origin);
|
|
725
764
|
const journal = readJournal(ctx.root, ctx.config.denyPaths ?? []);
|
|
726
|
-
const planned = plan(ctx, request.ops, journal);
|
|
765
|
+
const planned = plan(ctx, request.ops, journal, origin);
|
|
727
766
|
receipt.entries = planned.map(entry => ({ id: entry.id || "(assigned at append)", op: entry.op, ...(entry.op !== "subject" ? { rev: Number(entry.payload.rev) } : {}) }));
|
|
728
767
|
receipt.ok = true;
|
|
729
768
|
return receipt;
|
|
730
769
|
}
|
|
731
770
|
if (!heldRoot) lock = acquire(ctx.root);
|
|
732
771
|
const journal = readJournal(ctx.root, ctx.config.denyPaths ?? []);
|
|
733
|
-
const planned = plan(ctx, request.ops, journal);
|
|
772
|
+
const planned = plan(ctx, request.ops, journal, origin);
|
|
734
773
|
if (journal.entries + planned.length > MAX_JOURNAL_ENTRIES) refuse("V09", `the journal would exceed ${MAX_JOURNAL_ENTRIES} entries; appends refuse rather than rotate history`);
|
|
735
774
|
// An over-estimate only, so a segment chosen on it has room for the real lines; `parents` cost their own bytes.
|
|
736
775
|
const estimate = planned.reduce((sum, entry) => sum + bytes(canonical(entry.payload)) + 1024 + (entry.parents ?? []).reduce((cost, parent) => cost + parent.length + 4, 0), 0);
|
|
@@ -762,6 +801,7 @@ function appendAssertionsInternal(home: string, request: AssertRequest, options:
|
|
|
762
801
|
const buffer = Buffer.from(lines.join(""));
|
|
763
802
|
// The journal bound is checked on the bytes that will be written, before the file is opened.
|
|
764
803
|
if (journal.bytes + buffer.length > MAX_JOURNAL_BYTES) refuse("V09", `the journal would exceed ${MAX_JOURNAL_BYTES} bytes once this batch is written; appends refuse rather than rotate history`);
|
|
804
|
+
if (origin) verifyOrigin(ctx, origin);
|
|
765
805
|
const dir = join(ctx.root, ASSERTIONS_DIR);
|
|
766
806
|
let createdDir = false;
|
|
767
807
|
try { const stat = lstatSync(dir); if (stat.isSymbolicLink() || !stat.isDirectory()) refuse("V04", "assertions/ must be a plain directory; move the file or link aside"); }
|
package/src/cli-output.ts
CHANGED
|
@@ -7,6 +7,7 @@ import type { ResolvedHome } from "./home.ts";
|
|
|
7
7
|
import type { PiiMatrix, PiiRow } from "./pii.ts";
|
|
8
8
|
import { effectivePii, type RecoveryReport } from "./registry.ts";
|
|
9
9
|
import type { SetupReport } from "./setup.ts";
|
|
10
|
+
import type { SkillInstallReport } from "./skills-install.ts";
|
|
10
11
|
import { blocks, clean, fields, heading, issueTable, marker, nextCommand, paragraph as formatParagraph, plural, shellWord, status, table, tone, type CellInput, type TextOptions, type Tone } from "./text-output.ts";
|
|
11
12
|
import { MAX_RATIO_NOTES } from "./vault-index.ts";
|
|
12
13
|
import type { VaultStats } from "./vault-stats.ts";
|
|
@@ -147,10 +148,10 @@ export function renderManifest(m: Manifest, o: TextOptions): string {
|
|
|
147
148
|
|
|
148
149
|
/** `apply` is the exact command that applies a dry run. */
|
|
149
150
|
export function renderSetup(r: SetupReport, o: TextOptions, apply?: string): string {
|
|
150
|
-
const rows = [...r.actions.map(a => ({ host: a.target, ...a })), ...(r.console ? [{ host: "console", ...r.console }] : [])];
|
|
151
|
-
const reasons = rows.some(a => a.reason), refused = rows.filter(a => a.change === "refused").length, pending = rows.some(a => !["none", "unchanged", "refused"].includes(a.change));
|
|
151
|
+
const rows = [...r.actions.map(a => ({ host: a.target, ...a })), ...(r.console ? [{ host: "console", ...r.console }] : []), ...(r.skills ?? []).flatMap(s => s.report ? s.report.actions.map(a => ({ host: `${s.target} skill`, file: a.path, change: a.change, reason: a.reason })) : [{ host: `${s.target} skill`, file: "-", change: s.refused ? "refused" : "none", reason: s.reason }])];
|
|
152
|
+
const reasons = rows.some(a => a.reason), refused = rows.filter(a => a.change === "refused").length, pending = rows.some(a => !["none", "unchanged", "absent", "refused", "foreign", "modified"].includes(a.change));
|
|
152
153
|
const title = r.mode === "dry-run" ? "dry run: nothing written" : r.applied ? (r.mode === "apply" ? "setup applied" : "setup undone") : "unchanged: nothing to do";
|
|
153
|
-
const changeTone = (change: string) =>
|
|
154
|
+
const changeTone = (change: string) => ["refused", "foreign", "modified"].includes(change) ? "fail" : ["none", "unchanged"].includes(change) ? "muted" : "info";
|
|
154
155
|
return blocks(paragraph(title, o, r.applied ? "ok" : undefined),
|
|
155
156
|
fields([["server", [r.entry.command, ...r.entry.args].map(shellWord).join(" ")], ["root", r.root ? `${r.root.path} (${r.root.version})` : undefined]], o),
|
|
156
157
|
rows.length ? table(["HOST", "CHANGE", "PATH", ...(reasons ? ["REASON"] : [])], rows.map(a => [a.host, tone(a.change, changeTone(a.change)), a.file, a.reason]), o) : undefined,
|
|
@@ -158,3 +159,9 @@ export function renderSetup(r: SetupReport, o: TextOptions, apply?: string): str
|
|
|
158
159
|
refused ? paragraph(`${plural(refused, "host")} refused; see REASON.`, o, "fail") : undefined,
|
|
159
160
|
r.mode === "dry-run" && pending && apply ? nextCommand("apply", apply, o) : undefined);
|
|
160
161
|
}
|
|
162
|
+
|
|
163
|
+
/** Human-readable summary for an exported skill tree. */
|
|
164
|
+
export function renderSkillsExport(report: SkillInstallReport, o: TextOptions): string {
|
|
165
|
+
const color = (change: string): Tone => ["foreign", "modified", "refused"].includes(change) ? "fail" : ["unchanged", "absent"].includes(change) ? "muted" : "info";
|
|
166
|
+
return blocks(heading(`skills export: ${clean(report.root)}`, o), table(["NAME", "CHANGE", "PATH", "REASON"], report.actions.map(action => [action.name, tone(action.change, color(action.change)), action.path, action.reason]), o));
|
|
167
|
+
}
|