pi-memory-strata 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 memory-strata contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # Memory Strata — 四层分层记忆架构
2
+
3
+ > Four-layer stratified memory architecture for long-horizon AI agent projects.
4
+ > Solves critical fact forgetting, memory bloat, and knowledge sedimentation failures.
5
+
6
+ ---
7
+
8
+ ## Architecture
9
+
10
+ ```
11
+ L1 System Injection MEMORY.md — key points + anchors (auto-loaded every session)
12
+ L2 Project Core project-core.md — stable facts + ADR (rarely changes)
13
+ L3 Dev Status dev-status.md — progress/params/issues (updates with progress)
14
+ L4 Daily Journal YYYY-MM-DD.md — session log (per-session)
15
+ ```
16
+
17
+ ## Three Mechanisms
18
+
19
+ ### 1. Auto-Distillation (Episodic → Semantic)
20
+
21
+ - L4→L3: milestone completed, or referenced across ≥2 sessions
22
+ - L3→L2: stable ≥1 month + confirmed fact + likely needed in future
23
+ - L2→L1: useful beyond this project (user preferences, general lessons)
24
+
25
+ ### 2. Memory Strength Decay (`last_used`)
26
+
27
+ - Tag entries with `[last_used: YYYY-MM-DD]`
28
+ - >14 days unused → ⚡ rarely used
29
+ - >30 days unused → auto-archive
30
+
31
+ ### 3. Zettelkasten Link Enhancement
32
+
33
+ - Bidirectional `[[...]]` links between L2↔L3
34
+ - Check link integrity with the distillation script
35
+
36
+ ## Quick Start
37
+
38
+ ### 1. Initialize a project
39
+
40
+ ```bash
41
+ npx pi-memory-strata init-project <project-name>
42
+ ```
43
+
44
+ ### 2. Run daily maintenance (or schedule with cron)
45
+
46
+ ```bash
47
+ npx pi-memory-strata maintain --vault /path/to/vault
48
+ ```
49
+
50
+ ### 3. Check memory health
51
+
52
+ ```bash
53
+ npx pi-memory-strata check --vault /path/to/vault
54
+ ```
55
+
56
+ ## Installation
57
+
58
+ ### As Pi Extension
59
+
60
+ ```bash
61
+ pi install npm:pi-memory-strata
62
+ ```
63
+
64
+ ### As npm package
65
+
66
+ ```bash
67
+ npm install -g pi-memory-strata
68
+ ```
69
+
70
+ ### Direct usage (no install)
71
+
72
+ ```bash
73
+ npx pi-memory-strata <command>
74
+ ```
75
+
76
+ ## Programmatic API
77
+
78
+ ```typescript
79
+ import { MemoryStrata } from 'pi-memory-strata';
80
+
81
+ const strata = new MemoryStrata({
82
+ vaultPath: '/path/to/obsidian-vault',
83
+ autoArchiveDays: 30,
84
+ staleWarningDays: 14,
85
+ });
86
+
87
+ // Run distillation check
88
+ const check = await strata.check();
89
+ console.log(check.ok);
90
+
91
+ // Run daily maintenance
92
+ const report = await strata.maintain();
93
+ console.log(report.health);
94
+
95
+ // Initialize new project
96
+ strata.initProject('my-project');
97
+ ```
98
+
99
+ ## Vault Structure
100
+
101
+ ```
102
+ obsidian-vault/
103
+ ├── 00-brain/
104
+ │ └── MEMORY.md # L1: System injection
105
+ ├── 10-journal/
106
+ │ ├── maintenance/ # Daily maintenance reports
107
+ │ ├── summary/ # Auto-generated daily summaries
108
+ │ └── 2026-01-01.md # L4: Daily logs
109
+ ├── 20-projects/
110
+ │ └── my-project/
111
+ │ ├── dev-status.md # L3: Development status
112
+ │ └── project-core.md # L2: Project core archive
113
+ ├── 30-knowledge/
114
+ ├── 60-learnings/
115
+ │ └── archive/ # Auto-archived entries
116
+ ├── scripts/
117
+ │ ├── memory_distill_check.py
118
+ │ └── daily_memory_maintenance.py
119
+ └── templates/
120
+ ├── 01-status.md
121
+ └── 02-core.md
122
+ ```
123
+
124
+ ## Daily Maintenance (Automated)
125
+
126
+ Schedule daily maintenance with cron or systemd:
127
+
128
+ ```bash
129
+ # Every day at 09:30
130
+ 30 9 * * * npx pi-memory-strata maintain
131
+ ```
132
+
133
+ Maintenance performs:
134
+ 1. **Journal coverage check** — verify last 7 days have logs
135
+ 2. **Dev status freshness** — warn if >7 days without update
136
+ 3. **Core archive freshness** — warn if >30 days without update
137
+ 4. **Memory decay** — identify entries with stale `last_used`
138
+ 5. **Anchor integrity** — verify memory anchors exist
139
+ 6. **Bidirectional links** — check L2↔L3 link completeness
140
+ 7. **Auto-archive** — move >30d stale entries to `60-learnings/archive/`
141
+ 8. **Daily summary** — generate previous day's summary
142
+
143
+ ## Academic Context
144
+
145
+ | Concept | Source | This Package |
146
+ |---------|--------|-------------|
147
+ | Write-Manage-Read loop | arXiv:2603.07670 | W(journal) + M(distill/decay) + R(search) |
148
+ | Episodic→Semantic promotion | A-MEM (NeurIPS 2025) | L4→L3→L2 distillation |
149
+ | Memory strength decay | MemoryBank (2024) | `last_used` + 30-day archive |
150
+ | Zettelkasten linking | A-MEM | Obsidian `[[...]]` bidirectional links |
151
+ | Atomic facts | AtomMem (2026) | Memory anchors with consequence tags |
152
+
153
+ ## License
154
+
155
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { MemoryStrata } from './index.js';
4
+ const program = new Command();
5
+ program
6
+ .name('pi-memory-strata')
7
+ .description('Four-layer stratified memory architecture for long-horizon AI agent projects')
8
+ .version('0.1.0');
9
+ program
10
+ .command('check')
11
+ .description('Run distillation check on memory system')
12
+ .option('-v, --vault <path>', 'Path to Obsidian vault')
13
+ .action(async (options) => {
14
+ const strata = new MemoryStrata({ vaultPath: options.vault });
15
+ try {
16
+ const result = await strata.check();
17
+ console.log('Distillation check completed:', result.ok ? 'OK' : 'WARN');
18
+ if (!result.ok) {
19
+ process.exit(1);
20
+ }
21
+ }
22
+ catch (err) {
23
+ console.error('Check failed:', err instanceof Error ? err.message : String(err));
24
+ process.exit(1);
25
+ }
26
+ });
27
+ program
28
+ .command('maintain')
29
+ .description('Run daily maintenance routine')
30
+ .option('-v, --vault <path>', 'Path to Obsidian vault')
31
+ .option('--dry-run', 'Only check, do not modify')
32
+ .action(async (options) => {
33
+ const strata = new MemoryStrata({ vaultPath: options.vault });
34
+ try {
35
+ const report = await strata.maintain();
36
+ console.log('Maintenance completed:', report.date);
37
+ console.log('Health:', JSON.stringify(report.health, null, 2));
38
+ console.log('Issues:', report.issues.length);
39
+ console.log('Suggestions:', report.suggestions.length);
40
+ }
41
+ catch (err) {
42
+ console.error('Maintenance failed:', err instanceof Error ? err.message : String(err));
43
+ process.exit(1);
44
+ }
45
+ });
46
+ program
47
+ .command('init-project')
48
+ .description('Initialize a new project in the vault')
49
+ .argument('<name>', 'Project name')
50
+ .option('-v, --vault <path>', 'Path to Obsidian vault')
51
+ .action((name, options) => {
52
+ const strata = new MemoryStrata({ vaultPath: options.vault });
53
+ try {
54
+ strata.initProject(name);
55
+ console.log(`Project initialized: ${name}`);
56
+ }
57
+ catch (err) {
58
+ console.error('Init failed:', err instanceof Error ? err.message : String(err));
59
+ process.exit(1);
60
+ }
61
+ });
62
+ program.parse();
@@ -0,0 +1,21 @@
1
+ import type { MemoryConfig, MaintenanceReport, DistillCheckResult } from './types.js';
2
+ export declare class MemoryStrata {
3
+ private config;
4
+ private vaultPath;
5
+ constructor(config?: Partial<MemoryConfig>);
6
+ /**
7
+ * Run the Python distillation check script
8
+ */
9
+ check(): Promise<DistillCheckResult>;
10
+ /**
11
+ * Run the daily maintenance routine
12
+ */
13
+ maintain(): Promise<MaintenanceReport>;
14
+ /**
15
+ * Initialize a new project in the vault
16
+ */
17
+ initProject(projectName: string): void;
18
+ private parseCheckOutput;
19
+ private parseMaintenanceOutput;
20
+ }
21
+ export { MemoryConfig, MaintenanceReport, DistillCheckResult, ProjectInfo } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ import { execSync } from 'child_process';
2
+ import { existsSync } from 'fs';
3
+ import { resolve } from 'path';
4
+ export class MemoryStrata {
5
+ config;
6
+ vaultPath;
7
+ constructor(config) {
8
+ this.config = {
9
+ vaultPath: process.env.OBSIDIAN_VAULT_PATH || '',
10
+ autoArchiveDays: 30,
11
+ staleWarningDays: 14,
12
+ journalCheckDays: 7,
13
+ ...config,
14
+ };
15
+ this.vaultPath = this.config.vaultPath;
16
+ }
17
+ /**
18
+ * Run the Python distillation check script
19
+ */
20
+ async check() {
21
+ const scriptPath = resolve(import.meta.dirname, '../scripts/memory_distill_check.py');
22
+ if (!existsSync(scriptPath)) {
23
+ throw new Error(`Script not found: ${scriptPath}`);
24
+ }
25
+ const result = execSync(`python "${scriptPath}" --vault "${this.vaultPath}"`, { encoding: 'utf-8', cwd: this.vaultPath });
26
+ return this.parseCheckOutput(result);
27
+ }
28
+ /**
29
+ * Run the daily maintenance routine
30
+ */
31
+ async maintain() {
32
+ const scriptPath = resolve(import.meta.dirname, '../scripts/daily_memory_maintenance.py');
33
+ if (!existsSync(scriptPath)) {
34
+ throw new Error(`Maintenance script not found: ${scriptPath}`);
35
+ }
36
+ const result = execSync(`python "${scriptPath}" --vault "${this.vaultPath}"`, { encoding: 'utf-8', cwd: this.vaultPath });
37
+ return this.parseMaintenanceOutput(result);
38
+ }
39
+ /**
40
+ * Initialize a new project in the vault
41
+ */
42
+ initProject(projectName) {
43
+ const projectDir = resolve(this.vaultPath, '20-projects', projectName);
44
+ if (existsSync(projectDir)) {
45
+ throw new Error(`Project already exists: ${projectName}`);
46
+ }
47
+ // Copy templates
48
+ const templatesDir = resolve(import.meta.dirname, '../templates');
49
+ execSync(`mkdir -p "${projectDir}" && cp "${templatesDir}/01-status.md" "${projectDir}/dev-status.md" && cp "${templatesDir}/02-core.md" "${projectDir}/project-core.md"`, { encoding: 'utf-8' });
50
+ }
51
+ parseCheckOutput(output) {
52
+ // Parse the output of memory_distill_check.py
53
+ // This is a simplified parser - the actual implementation would parse the full output
54
+ return {
55
+ ok: !output.includes('MISSING') && !output.includes('STALE'),
56
+ projects: [],
57
+ journalMissingDays: [],
58
+ staleEntries: [],
59
+ missingAnchors: [],
60
+ };
61
+ }
62
+ parseMaintenanceOutput(output) {
63
+ // Parse the output of daily_memory_maintenance.py
64
+ const health = {
65
+ journalCoverage: output.includes('L4 journal') && output.includes('MISSING') ? 'warn' : 'ok',
66
+ devStatus: output.includes('dev status') && output.includes('STALE') ? 'warn' : 'ok',
67
+ coreArchive: output.includes('core archive') && output.includes('STALE') ? 'warn' : 'ok',
68
+ memoryDecay: output.includes('archiving') ? 'warn' : 'ok',
69
+ anchorIntegrity: output.includes('No anchor') ? 'warn' : 'ok',
70
+ bidirectionalLinks: output.includes('incomplete') ? 'warn' : 'ok',
71
+ };
72
+ return {
73
+ date: new Date().toISOString().split('T')[0],
74
+ health,
75
+ issues: [],
76
+ suggestions: [],
77
+ archivedCount: 0,
78
+ };
79
+ }
80
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Types for Pi Memory Strata extension
3
+ */
4
+ export interface MemoryVault {
5
+ root: string;
6
+ brain: string;
7
+ journal: string;
8
+ projects: string;
9
+ knowledge: string;
10
+ learnings: string;
11
+ templates: string;
12
+ scripts: string;
13
+ }
14
+ export interface MaintenanceReport {
15
+ date: string;
16
+ health: {
17
+ journalCoverage: 'ok' | 'warn';
18
+ devStatus: 'ok' | 'warn';
19
+ coreArchive: 'ok' | 'warn';
20
+ memoryDecay: 'ok' | 'warn';
21
+ anchorIntegrity: 'ok' | 'warn';
22
+ bidirectionalLinks: 'ok' | 'warn';
23
+ };
24
+ issues: string[];
25
+ suggestions: string[];
26
+ archivedCount: number;
27
+ summaryPath?: string;
28
+ }
29
+ export interface ProjectInfo {
30
+ name: string;
31
+ statusPath: string;
32
+ corePath: string;
33
+ lastStatusUpdate?: string;
34
+ lastCoreUpdate?: string;
35
+ daysSinceStatusUpdate?: number;
36
+ daysSinceCoreUpdate?: number;
37
+ bidirectionalLinks: boolean;
38
+ }
39
+ export interface DistillCheckResult {
40
+ ok: boolean;
41
+ projects: ProjectInfo[];
42
+ journalMissingDays: string[];
43
+ staleEntries: string[];
44
+ missingAnchors: string[];
45
+ }
46
+ export interface MemoryConfig {
47
+ vaultPath: string;
48
+ autoArchiveDays: number;
49
+ staleWarningDays: number;
50
+ journalCheckDays: number;
51
+ }
package/dist/types.js ADDED
@@ -0,0 +1,4 @@
1
+ /**
2
+ * Types for Pi Memory Strata extension
3
+ */
4
+ export {};
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "pi-memory-strata",
3
+ "version": "0.1.0",
4
+ "description": "Four-layer stratified memory architecture for long-horizon AI agent projects. Auto-distillation, memory decay, and Obsidian vault integration.",
5
+ "type": "module",
6
+ "piConfig": {
7
+ "configDir": ".pi"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "bin": {
12
+ "pi-memory-strata": "dist/cli.js"
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "scripts",
17
+ "templates",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsc",
23
+ "clean": "rm -rf dist",
24
+ "prepublishOnly": "npm run clean && npm run build"
25
+ },
26
+ "keywords": [
27
+ "pi",
28
+ "extension",
29
+ "memory",
30
+ "stratified-memory",
31
+ "obsidian",
32
+ "long-horizon",
33
+ "agent-memory"
34
+ ],
35
+ "author": "bailianfa",
36
+ "license": "MIT",
37
+ "dependencies": {
38
+ "commander": "^11.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "typescript": "^5.3.0",
42
+ "@types/node": "^20.0.0"
43
+ },
44
+ "engines": {
45
+ "node": ">=18.0.0"
46
+ }
47
+ }