wayform 0.1.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.
Files changed (47) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +262 -0
  3. package/dist/cli.js +65 -0
  4. package/dist/cli.js.map +1 -0
  5. package/dist/config.js +174 -0
  6. package/dist/config.js.map +1 -0
  7. package/dist/context-format.js +18 -0
  8. package/dist/context-format.js.map +1 -0
  9. package/dist/doctor.js +182 -0
  10. package/dist/doctor.js.map +1 -0
  11. package/dist/frontmatter.js +50 -0
  12. package/dist/frontmatter.js.map +1 -0
  13. package/dist/git-repo.js +166 -0
  14. package/dist/git-repo.js.map +1 -0
  15. package/dist/hook-clients.js +90 -0
  16. package/dist/hook-clients.js.map +1 -0
  17. package/dist/hook.js +95 -0
  18. package/dist/hook.js.map +1 -0
  19. package/dist/index.js +213 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/init-configs.js +119 -0
  22. package/dist/init-configs.js.map +1 -0
  23. package/dist/init-env.js +70 -0
  24. package/dist/init-env.js.map +1 -0
  25. package/dist/init-remote.js +155 -0
  26. package/dist/init-remote.js.map +1 -0
  27. package/dist/init.js +132 -0
  28. package/dist/init.js.map +1 -0
  29. package/dist/is-main.js +14 -0
  30. package/dist/is-main.js.map +1 -0
  31. package/dist/metrics.js +35 -0
  32. package/dist/metrics.js.map +1 -0
  33. package/dist/remote-read.js +57 -0
  34. package/dist/remote-read.js.map +1 -0
  35. package/dist/review-prompt.js +23 -0
  36. package/dist/review-prompt.js.map +1 -0
  37. package/dist/slug.js +19 -0
  38. package/dist/slug.js.map +1 -0
  39. package/dist/space-create.js +195 -0
  40. package/dist/space-create.js.map +1 -0
  41. package/dist/stop-hook.js +66 -0
  42. package/dist/stop-hook.js.map +1 -0
  43. package/dist/store.js +177 -0
  44. package/dist/store.js.map +1 -0
  45. package/dist/token-budget.js +35 -0
  46. package/dist/token-budget.js.map +1 -0
  47. package/package.json +39 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Skanda Ramanan
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,262 @@
1
+ # MemoryLayer
2
+
3
+ **Shared planning memory for teams that build with AI.** A decision made in one
4
+ person's Claude session is already loaded in their teammate's Cursor session —
5
+ automatically, at session start, with nobody pasting anything.
6
+
7
+ ```
8
+ you (Claude Code) teammate (Cursor)
9
+ │ │
10
+ │ "we decided X because Y" │ new session opens
11
+ ▼ ▼
12
+ write_context ──► shared git repo ──► session-start hook
13
+ (your repo, injects every decision
14
+ your history) as already-known context
15
+ ```
16
+
17
+ ## Why this exists
18
+
19
+ AI pair-programming has a memory problem, and it's worse in teams. Every session
20
+ starts cold. Every collaborator re-explains the same settled decisions to their
21
+ own agent, every day. The context that matters — *what we decided and why* —
22
+ lives in Slack scrollback and people's heads.
23
+
24
+ MemoryLayer fixes the loop with three properties nothing else combines:
25
+
26
+ - **Multiplayer.** One shared store per team. Your agent reads what your
27
+ teammate's agent wrote. Attribution is git commit authorship — you always know
28
+ who decided what, when.
29
+ - **Vendor-neutral.** Works identically across **Claude Code, Cursor, and
30
+ Codex** (plus any MCP client). The store, the tool contract, and the injected
31
+ context are byte-identical across tools — a decision written from Cursor lands
32
+ in a Claude session and vice versa. Switching AI tools never loses your
33
+ team's memory.
34
+ - **You own the data.** The store is a **private git repo in your account** —
35
+ append-only log, immutable commits, full history, `git log` as the audit
36
+ trail. We rent git's consistency model; we don't rebuild it. No vendor
37
+ database holds your team's decisions.
38
+
39
+ **The write model is deliberately curated:** a write is *"we decided X because
40
+ Y"* — settled decisions and durable context, not a firehose of reasoning
41
+ tokens. That's what keeps the store worth injecting into every session instead
42
+ of degrading into a junk drawer.
43
+
44
+ ---
45
+
46
+ ## Quickstart (local mode)
47
+
48
+ Three steps: install the CLI, create the shared repo, wire your project.
49
+
50
+ ### 1. Install the CLI (once per machine)
51
+
52
+ ```bash
53
+ git clone https://github.com/skandaramanan/MemoryLayer /tmp/memorylayer \
54
+ && npm install -g /tmp/memorylayer
55
+ ```
56
+
57
+ Requires Node ≥ 18. `dist/` is pre-built and committed, so no build step runs
58
+ on install.
59
+
60
+ > **Why not `npm install -g github:...`?** npm 10 has a git-global-install bug
61
+ > (the package is symlinked to an ephemeral cache dir that never gets checked
62
+ > out) that makes the one-liner fail with `command not found` or `ENOTDIR`.
63
+ > The clone-then-install path above uses npm's copy path and works everywhere.
64
+ > See [Troubleshooting](#troubleshooting).
65
+
66
+ ### 2. Create the shared context repo (once per team)
67
+
68
+ One person creates a **private** git repo (e.g. `yourteam-memory`) and grants
69
+ each collaborator push access. This is the team's memory; it starts empty. The
70
+ v1 "shared key" is simply git access to this repo — an HTTPS URL with a token,
71
+ or SSH. No accounts, no separate auth.
72
+
73
+ ### 3. Wire it into your project
74
+
75
+ From your project repo:
76
+
77
+ ```bash
78
+ memorylayer init
79
+ ```
80
+
81
+ `init` writes, idempotently and without clobbering existing config:
82
+
83
+ - **Session-start read hooks + MCP registration** for Claude Code
84
+ (`.claude/settings.json`, `.mcp.json`), Cursor (`.cursor/hooks.json`,
85
+ `.cursor/mcp.json`), and Codex (`.codex/hooks.json`; MCP is a printed block
86
+ to paste into `~/.codex/config.toml`, since Codex registers MCP globally)
87
+ - **End-of-turn write-review hooks** (the Stop hook — see
88
+ [The loop](#the-loop-how-reads-and-writes-actually-happen))
89
+ - Your per-user, **gitignored** `.memorylayer-hook.env` (identity + repo URL —
90
+ secrets never enter git)
91
+
92
+ One person commits the project configs; each teammate runs `memorylayer init`
93
+ once to set their own identity. Done — the next coding session in that project
94
+ starts with the team's context already loaded.
95
+
96
+ **Verify the round-trip:** from a session, say *"record this decision: testing
97
+ MemoryLayer, because we just set it up."* Then have a teammate (or a second
98
+ machine) open a fresh session — the decision should be in their context without
99
+ anyone pasting it. That round-trip is the product.
100
+
101
+ ---
102
+
103
+ ## Hosted gateway (beta)
104
+
105
+ The local mode above needs each member to hold a git token. The **hosted
106
+ gateway** removes even that: a stateless Cloudflare Worker exposes the same two
107
+ tools over MCP Streamable HTTP, storing to the same kind of private GitHub repo
108
+ via a GitHub App — so joining a team space becomes *paste a URL and a token*.
109
+
110
+ - **Same store, same format.** Gateway-written entries are byte-identical to
111
+ local ones (both planes compile the same serialization module). A space's
112
+ repo can serve hosted members and local git-token members simultaneously.
113
+ - **Tenant isolation by construction.** One private repo per space; the GitHub
114
+ App is installed on exactly that repo; every request resolves to a
115
+ per-installation token that GitHub itself scopes to that one repo. No API
116
+ surface accepts a repo/space parameter, so a routing bug cannot cross
117
+ tenants. Member tokens are stored only as SHA-256 hashes.
118
+ - **Works with closed clients.** Anything that speaks MCP over HTTP — including
119
+ clients that can't run local hooks — configures:
120
+
121
+ ```json
122
+ { "url": "https://<your-gateway>/mcp",
123
+ "headers": { "Authorization": "Bearer mlk_..." } }
124
+ ```
125
+
126
+ Endpoints, tenancy model, limits, and the deploy runbook live in
127
+ [gateway/README.md](gateway/README.md). Client-side hook shims for the gateway
128
+ (`init --remote`) are the next planned increment.
129
+
130
+ ---
131
+
132
+ ## The two tools
133
+
134
+ Everything reads and writes through one MCP contract (identical in local stdio
135
+ and hosted HTTP modes):
136
+
137
+ | Tool | What it does |
138
+ |---|---|
139
+ | `read_context(project, budget_tokens?)` | Pull latest and return the projected context — every recorded decision, in write order, packed to a token budget (default 4000) so reads never flood a session as the store grows. |
140
+ | `write_context(project, type, payload)` | Append one decision (`type: "decision"`) or durable background (`type: "context"`) as its own file, commit, push. The commit is the event; the author is the attribution. |
141
+
142
+ Each write is its own file under `context/<project>/<author>/`, so concurrent
143
+ writers never touch the same file and never merge-conflict. Many working repos
144
+ may share one memory repo (kept separate inside it by `context/<project>/`).
145
+
146
+ ## The loop — how reads and writes actually happen
147
+
148
+ **Reads are guaranteed, not hoped for.** MCP alone is pull-based — an agent
149
+ reads only when it decides to. The session-start hook removes that dependency:
150
+ it injects the project's context before the agent does anything. Hooks are
151
+ **project-scoped on purpose** — they fire only in this project's coding
152
+ sessions, never in unrelated chats.
153
+
154
+ **Writes have three paths, softest first:**
155
+
156
+ 1. **Say it** (any client, incl. Claude Desktop): *"record this decision: X
157
+ because Y."* A direct command the model complies with near-reliably.
158
+ 2. **`/remember`** (Claude Code / Cursor): one-word gesture; ships in
159
+ `.claude/commands/remember.md`. `/remember we decided X because Y`, or bare
160
+ `/remember` to record the last settled decision.
161
+ 3. **End-of-turn self-review** (Claude Code / Cursor / Codex): a Stop hook asks
162
+ the model at each turn's end — *"did this turn settle a decision that isn't
163
+ recorded? If yes, write it; if not, do nothing."* This closes the weak half
164
+ of the loop (models don't spontaneously notice). Loop-guarded to fire at
165
+ most once per turn.
166
+
167
+ **Everything runtime is fail-open.** Offline, bad config, empty store — hooks
168
+ emit their client's no-op and exit 0. A broken memory layer can never break a
169
+ coding session. (The flip side: failures are quiet — that's what `doctor` is
170
+ for.)
171
+
172
+ **Claude Desktop** has no hook system, so it's MCP-pull-only: register
173
+ `memorylayer` as a stdio server (or point Desktop at the hosted gateway) and it
174
+ reads when the model chooses to — path 1 is your write path there.
175
+
176
+ ## Configuration (`.memorylayer-hook.env`)
177
+
178
+ Written by `init`, per-user, gitignored, self-loaded from the project root at
179
+ runtime. Keys are an **allowlist** — a crafted file cannot inject other env
180
+ into hook subprocesses:
181
+
182
+ | Var | Required | Meaning |
183
+ |-----|----------|---------|
184
+ | `CONTEXT_REPO_URL` | yes | Shared context repo URL (may embed a token). |
185
+ | `MEMORYLAYER_AUTHOR` | yes | Your name — commit author / attribution. |
186
+ | `MEMORYLAYER_AUTHOR_EMAIL` | no | Commit email. Defaults from author name. |
187
+ | `MEMORYLAYER_PROJECT` | no | Project/space name. Default: repo directory name. |
188
+ | `CONTEXT_REPO_PATH` | no | Local clone path. Default: keyed per repo URL under `$XDG_DATA_HOME/memorylayer/clones/<repo-slug>-<hash>` (falls back to `~/.local/share/...`), so two spaces can never share a clone. |
189
+ | `MEMORYLAYER_READ_BUDGET_TOKENS` | no | Read token budget. Default 4000; `<=0` = unlimited. |
190
+ | `MEMORYLAYER_AUTO_PUSH` | no | `false` to skip pushing (local smoke tests). |
191
+
192
+ ## Diagnostics
193
+
194
+ ```bash
195
+ memorylayer doctor
196
+ ```
197
+
198
+ Read-only. Checks the env file, resolved config, clone health and origin,
199
+ remote connectivity/auth, unpushed commits, and the default project name.
200
+ Tokens embedded in URLs are redacted before printing. Run it whenever a read or
201
+ write "silently" does nothing — fail-open means problems hide here first.
202
+
203
+ ## Security & data ownership
204
+
205
+ - **Local mode:** your data never transits anything but git between your
206
+ machine and your own private repo. The env allowlist blocks env injection;
207
+ project/author names are slugged so a hostile name can't path-traverse out of
208
+ `context/`; error output redacts embedded tokens.
209
+ - **Hosted mode:** the gateway is a stateless proxy — the source of truth stays
210
+ a private GitHub repo in *your* account. The App holds Contents-only
211
+ permission on exactly one repo per space; member bearer tokens are stored
212
+ only as SHA-256 hashes; the Worker holds secrets in Cloudflare's secret
213
+ store, never in code or git.
214
+ - **Trust boundary to know about:** everything a space member writes is
215
+ injected into every member's sessions. You trust the people in your space —
216
+ that's the model, stated plainly.
217
+
218
+ ## Troubleshooting
219
+
220
+ | Symptom | Cause & fix |
221
+ |---|---|
222
+ | `memorylayer: command not found` right after `npm install -g github:...` | npm 10 git-global-install bug: the global bin points at an ephemeral cache clone with no files. Fix: the clone-then-install path from the Quickstart, or `npm pack` + `npm install -g ./memorylayer-*.tgz`. |
223
+ | `ENOTDIR` reinstalling over a previous failed install | Same bug, stale symlink. Remove the target dir shown in the error, then clone-then-install. |
224
+ | Reads/writes silently do nothing | `memorylayer doctor`. Most common: missing `.memorylayer-hook.env`, no repo access, or unpushed local commits (self-heals on next read). |
225
+ | Teammates still see old behavior after an upgrade | The fix lives in the **global binary** — each teammate must reinstall it (committed project configs aren't enough), and a running MCP server needs a restart to pick it up. |
226
+ | macOS `curl` fails TLS against the hosted gateway (`workers.dev`) | LibreSSL negotiation quirk — add `--tlsv1.2`. Client-side only; SDK-based MCP clients are unaffected. |
227
+
228
+ ## Project status
229
+
230
+ Working and in daily two-person dogfood; hosted gateway deployed and
231
+ smoke-tested end-to-end (including live interop: a gateway-written entry read
232
+ byte-intact by the local tool). Currently running a multi-week reliance pilot —
233
+ the success signal is a collaborator who **stops re-explaining decisions**
234
+ because they trust the shared space.
235
+
236
+ **Deliberately not built yet** (gated on the pilot proving pull): context
237
+ graph/index, dashboard UI, accounts/RBAC, summarization/RAG, custom merge
238
+ engine (git *is* the merge engine). Next increments: gateway client shims
239
+ (`init --remote`), space-provisioning CLI.
240
+
241
+ ## Repo layout
242
+
243
+ ```
244
+ src/ local CLI + stdio MCP server (init, hooks, store, doctor)
245
+ gateway/ hosted gateway — Cloudflare Worker (own README + runbook)
246
+ dist/ pre-built JS, committed (installs need no toolchain)
247
+ docs/plans/ implementation plans docs/specs/ design specs
248
+ docs/roadmap/ production + graph-store roadmaps
249
+ test/ node:test suites (gateway has its own under gateway/test/)
250
+ ```
251
+
252
+ ## Development
253
+
254
+ ```bash
255
+ npm test # build + full local suite, lint: npm run lint
256
+ npm run test:gateway # gateway suite (Node >= 20)
257
+ memorylayer --help # subcommands: init, hook, stop-review, doctor
258
+ ```
259
+
260
+ Both planes share the entry format modules (`src/frontmatter.ts`,
261
+ `src/slug.ts`, `src/token-budget.ts`) — change the format in one place or not
262
+ at all.
package/dist/cli.js ADDED
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * The single `wayform` command. Routes subcommands so the tool is one
4
+ * installable binary (no bash launchers, no separate entrypoints to wire):
5
+ *
6
+ * wayform -> MCP server (default)
7
+ * wayform hook <client> -> read hook
8
+ * wayform stop-review <client> -> Stop/write-review hook
9
+ * wayform init [flags] -> installer (add --remote for hosted members)
10
+ * wayform doctor -> local diagnostics
11
+ * wayform space create [flags] -> Plan C: provision a new hosted space
12
+ *
13
+ * `hook`/`stop-review` set MEMORYLAYER_HOOK_CLIENT from the positional arg, then
14
+ * delegate to the neutral run functions (which self-load .memorylayer-hook.env).
15
+ */
16
+ import { loadHookEnv } from "./config.js";
17
+ import { runServer } from "./index.js";
18
+ import { runHook } from "./hook.js";
19
+ import { runStopHook } from "./stop-hook.js";
20
+ import { runInit } from "./init.js";
21
+ import { runDoctor } from "./doctor.js";
22
+ import { runSpaceCreate } from "./space-create.js";
23
+ async function main() {
24
+ // Self-load .memorylayer-hook.env from the project cwd for every subcommand,
25
+ // so the command is self-contained (no bash launcher). loadConfig stays pure.
26
+ loadHookEnv();
27
+ const [sub, ...rest] = process.argv.slice(2);
28
+ switch (sub) {
29
+ case "hook":
30
+ if (rest[0])
31
+ process.env.MEMORYLAYER_HOOK_CLIENT = rest[0];
32
+ await runHook();
33
+ return;
34
+ case "stop-review":
35
+ if (rest[0])
36
+ process.env.MEMORYLAYER_HOOK_CLIENT = rest[0];
37
+ await runStopHook();
38
+ return;
39
+ case "init":
40
+ await runInit(rest);
41
+ return;
42
+ case "doctor":
43
+ await runDoctor();
44
+ return;
45
+ case "space":
46
+ if (rest[0] === "create") {
47
+ await runSpaceCreate(rest.slice(1));
48
+ return;
49
+ }
50
+ console.error(`Unknown "space" subcommand "${rest[0]}". Use: wayform space create --space <name> --owner <owner> --repo <repo> --gateway <url>`);
51
+ process.exit(1);
52
+ return;
53
+ case undefined:
54
+ await runServer();
55
+ return;
56
+ default:
57
+ console.error(`Unknown command "${sub}". Use: wayform [hook|stop-review|init|doctor|space] …`);
58
+ process.exit(1);
59
+ }
60
+ }
61
+ main().catch((err) => {
62
+ console.error(err instanceof Error ? err.message : String(err));
63
+ process.exit(1);
64
+ });
65
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,KAAK,UAAU,IAAI;IACjB,6EAA6E;IAC7E,8EAA8E;IAC9E,WAAW,EAAE,CAAC;IAEd,MAAM,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;IAE7C,QAAQ,GAAG,EAAE,CAAC;QACZ,KAAK,MAAM;YACT,IAAI,IAAI,CAAC,CAAC,CAAC;gBAAE,OAAO,CAAC,GAAG,CAAC,uBAAuB,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YAC3D,MAAM,OAAO,EAAE,CAAC;YAChB,OAAO;QACT,KAAK,aAAa;YAChB,IAAI,IAAI,CAAC,CAAC,CAAC;gBAAE,OAAO,CAAC,GAAG,CAAC,uBAAuB,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;YAC3D,MAAM,WAAW,EAAE,CAAC;YACpB,OAAO;QACT,KAAK,MAAM;YACT,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;YACpB,OAAO;QACT,KAAK,QAAQ;YACX,MAAM,SAAS,EAAE,CAAC;YAClB,OAAO;QACT,KAAK,OAAO;YACV,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,QAAQ,EAAE,CAAC;gBACzB,MAAM,cAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;gBACpC,OAAO;YACT,CAAC;YACD,OAAO,CAAC,KAAK,CACX,+BAA+B,IAAI,CAAC,CAAC,CAAC,2FAA2F,CAClI,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAChB,OAAO;QACT,KAAK,SAAS;YACZ,MAAM,SAAS,EAAE,CAAC;YAClB,OAAO;QACT;YACE,OAAO,CAAC,KAAK,CACX,oBAAoB,GAAG,wDAAwD,CAChF,CAAC;YACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACH,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;IACnB,OAAO,CAAC,KAAK,CAAC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IAChE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
package/dist/config.js ADDED
@@ -0,0 +1,174 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ import fs from "node:fs";
4
+ import crypto from "node:crypto";
5
+ import { DEFAULT_BUDGET_TOKENS } from "./token-budget.js";
6
+ function required(name) {
7
+ const v = process.env[name];
8
+ if (!v || v.trim() === "") {
9
+ throw new Error(`Missing required env var ${name}. See README for Wayform configuration.`);
10
+ }
11
+ return v.trim();
12
+ }
13
+ /**
14
+ * The ONLY env keys `loadHookEnv` will set from the file. This is a security
15
+ * allowlist, not just tidiness: `.memorylayer-hook.env` lives in a project repo
16
+ * and can be attacker-controlled (a malicious repo could commit one despite the
17
+ * gitignore). Since the hooks fire on opening any wired project and then spawn
18
+ * `git`/`node` subprocesses, an unrestricted loader would let a crafted file
19
+ * inject process-hijacking vars (NODE_OPTIONS, PATH, GIT_*, LD_PRELOAD, …) and
20
+ * reach code execution. We only ever set MemoryLayer's own config keys.
21
+ */
22
+ const HOOK_ENV_ALLOWLIST = new Set([
23
+ "CONTEXT_REPO_URL",
24
+ "CONTEXT_REPO_PATH",
25
+ "MEMORYLAYER_AUTHOR",
26
+ "MEMORYLAYER_AUTHOR_EMAIL",
27
+ "MEMORYLAYER_PROJECT",
28
+ "MEMORYLAYER_AUTO_PUSH",
29
+ "MEMORYLAYER_HOOK_CLIENT",
30
+ "MEMORYLAYER_READ_BUDGET_TOKENS",
31
+ "MEMORYLAYER_GATEWAY_URL",
32
+ "MEMORYLAYER_GATEWAY_TOKEN",
33
+ ]);
34
+ /**
35
+ * Load `.memorylayer-hook.env` (KEY=VALUE lines) from `cwd` into process.env,
36
+ * for allowlisted keys NOT already set. This replaces the old bash launcher's
37
+ * `set -a; . file` so the `memorylayer` command is self-contained. Called once
38
+ * at the CLI entry point (cli.ts) so every subcommand sees it, while `loadConfig`
39
+ * stays pure (env-only) and a directly-spawned `dist/hook.js` still fail-opens
40
+ * with no config. Only keys in HOOK_ENV_ALLOWLIST are honored — everything else
41
+ * (NODE_OPTIONS, PATH, …) is ignored, so an attacker-controlled file in a cloned
42
+ * repo cannot hijack the git/node subprocesses the hooks spawn. Silent no-op if
43
+ * the file is absent or unreadable — never throws.
44
+ */
45
+ export function loadHookEnv(cwd = process.cwd()) {
46
+ const file = path.join(cwd, ".memorylayer-hook.env");
47
+ let text;
48
+ try {
49
+ text = fs.readFileSync(file, "utf8");
50
+ }
51
+ catch {
52
+ return; // absent/unreadable — nothing to load.
53
+ }
54
+ for (const rawLine of text.split(/\r?\n/)) {
55
+ const line = rawLine.trim();
56
+ if (!line || line.startsWith("#"))
57
+ continue;
58
+ const eq = line.indexOf("=");
59
+ if (eq <= 0)
60
+ continue;
61
+ const key = line.slice(0, eq).trim();
62
+ const value = line.slice(eq + 1).trim();
63
+ if (!HOOK_ENV_ALLOWLIST.has(key))
64
+ continue; // ignore unknown/dangerous keys
65
+ if (process.env[key] === undefined)
66
+ process.env[key] = value;
67
+ }
68
+ }
69
+ /**
70
+ * Normalize a git remote URL to a stable identity: host+path only, lowercased,
71
+ * credentials/token dropped, no trailing `.git` or slashes. So the same repo via
72
+ * token-embedded HTTPS, bare HTTPS, or SSH maps to ONE identity — and a rotated
73
+ * token never changes it (nor leaks into a derived directory name).
74
+ */
75
+ export function normalizeRepoUrl(url) {
76
+ let s = url.trim();
77
+ const scp = /^[^/@]+@([^:/]+):(.+)$/.exec(s); // git@host:org/repo(.git)
78
+ if (scp) {
79
+ s = `${scp[1]}/${scp[2]}`;
80
+ }
81
+ else {
82
+ try {
83
+ const u = new URL(s);
84
+ s = `${u.host}${u.pathname}`; // u.host excludes userinfo → token dropped
85
+ }
86
+ catch {
87
+ // Not a parseable URL (e.g. a bare test token); fall through with s as-is.
88
+ }
89
+ }
90
+ return s
91
+ .toLowerCase()
92
+ .replace(/\.git$/, "")
93
+ .replace(/^\/+|\/+$/g, "");
94
+ }
95
+ /**
96
+ * Filesystem-safe, collision-proof directory key for a repo's local clone:
97
+ * `<repo-name-slug>-<hash8>`. The readable prefix aids humans browsing the
98
+ * clones dir; the hash of the normalized URL guarantees uniqueness even when two
99
+ * repo names slugify identically.
100
+ */
101
+ export function cloneKey(repoUrl) {
102
+ const normalized = normalizeRepoUrl(repoUrl);
103
+ const hash = crypto
104
+ .createHash("sha256")
105
+ .update(normalized)
106
+ .digest("hex")
107
+ .slice(0, 8);
108
+ const lastSeg = normalized.split("/").pop() || "repo";
109
+ const slug = lastSeg.replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "repo";
110
+ return `${slug}-${hash}`;
111
+ }
112
+ /**
113
+ * Base directory for MemoryLayer's local state, XDG-compliant. Clones live in
114
+ * the DATA bucket (not cache): a clone can transiently hold unpushed commits
115
+ * (the offline / selfHealPush path), so it must survive cache cleaners.
116
+ * Resolution: MEMORYLAYER_HOME > $XDG_DATA_HOME/memorylayer > ~/.local/share/memorylayer.
117
+ */
118
+ function dataHome() {
119
+ const explicit = process.env.MEMORYLAYER_HOME?.trim();
120
+ if (explicit)
121
+ return explicit;
122
+ const xdg = process.env.XDG_DATA_HOME?.trim();
123
+ if (xdg)
124
+ return path.join(xdg, "memorylayer");
125
+ return path.join(os.homedir(), ".local", "share", "memorylayer");
126
+ }
127
+ /**
128
+ * Default project/space name for the hooks when MEMORYLAYER_PROJECT is unset:
129
+ * the current repo's directory name (the same default `init` writes). A repo
130
+ * that has a valid CONTEXT_REPO_URL but a missing project env therefore lands in
131
+ * its OWN namespace instead of silently colliding in another project's — the
132
+ * previous hardcoded literal "memorylayer" quietly merged such a repo's entries
133
+ * into the dogfood project's namespace. Slugging happens downstream in the
134
+ * store; this returns the raw basename, and "unknown" only for a rootless cwd.
135
+ */
136
+ export function defaultProject(cwd = process.cwd()) {
137
+ return path.basename(cwd) || "unknown";
138
+ }
139
+ export function loadConfig() {
140
+ const author = required("MEMORYLAYER_AUTHOR");
141
+ const gatewayUrl = process.env.MEMORYLAYER_GATEWAY_URL?.trim().replace(/\/+$/, "") ||
142
+ undefined;
143
+ const gatewayToken = process.env.MEMORYLAYER_GATEWAY_TOKEN?.trim() || undefined;
144
+ const hasGateway = Boolean(gatewayUrl && gatewayToken);
145
+ // Gateway-only members have no local clone. CONTEXT_REPO_URL is optional when a
146
+ // gateway is configured; without a gateway it stays required (local-only mode).
147
+ // We use "" as a clear "no clone" sentinel rather than making repoUrl/repoPath
148
+ // optional, which would ripple `string | undefined` through store/git-repo/
149
+ // metrics/doctor. The clone is never touched in gateway-only mode — the hook
150
+ // guard (hook.ts) and the metrics guard (metrics.ts) enforce that.
151
+ const repoUrl = hasGateway
152
+ ? process.env.CONTEXT_REPO_URL?.trim() || ""
153
+ : required("CONTEXT_REPO_URL");
154
+ const repoPath = repoUrl
155
+ ? process.env.CONTEXT_REPO_PATH?.trim() ||
156
+ path.join(dataHome(), "clones", cloneKey(repoUrl))
157
+ : "";
158
+ const rawBudget = Number(process.env.MEMORYLAYER_READ_BUDGET_TOKENS);
159
+ const readBudgetTokens = Number.isFinite(rawBudget) && rawBudget > 0
160
+ ? rawBudget
161
+ : DEFAULT_BUDGET_TOKENS;
162
+ return {
163
+ repoUrl,
164
+ repoPath,
165
+ author,
166
+ authorEmail: process.env.MEMORYLAYER_AUTHOR_EMAIL?.trim() ||
167
+ `${author.replace(/\s+/g, ".").toLowerCase()}@memorylayer.local`,
168
+ autoPush: (process.env.MEMORYLAYER_AUTO_PUSH?.trim() || "true") !== "false",
169
+ readBudgetTokens,
170
+ gatewayUrl,
171
+ gatewayToken,
172
+ };
173
+ }
174
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AA4B1D,SAAS,QAAQ,CAAC,IAAY;IAC5B,MAAM,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC5B,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAA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U,IAAI,YAAY,CAAC,CAAC;IAEvD,gFAAgF;IAChF,gFAAgF;IAChF,+EAA+E;IAC/E,4EAA4E;IAC5E,6EAA6E;IAC7E,mEAAmE;IACnE,MAAM,OAAO,GAAG,UAAU;QACxB,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,EAAE,IAAI,EAAE,IAAI,EAAE;QAC5C,CAAC,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;IACjC,MAAM,QAAQ,GAAG,OAAO;QACtB,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,EAAE,IAAI,EAAE;YACrC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,EAAE,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;QACpD,CAAC,CAAC,EAAE,CAAC;IAEP,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;IACrE,MAAM,gBAAgB,GACpB,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,SAAS,GAAG,CAAC;QACzC,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,qBAAqB,CAAC;IAE5B,OAAO;QACL,OAAO;QACP,QAAQ;QACR,MAAM;QACN,WAAW,EACT,OAAO,CAAC,GAAG,CAAC,wBAAwB,EAAE,IAAI,EAAE;YAC5C,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,oBAAoB;QAClE,QAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,qBAAqB,EAAE,IAAI,EAAE,IAAI,MAAM,CAAC,KAAK,OAAO;QAC3E,gBAAgB;QAChB,UAAU;QACV,YAAY;KACb,CAAC;AACJ,CAAC"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Render a project's entries into the markdown block that read_context returns
3
+ * and the session-start hook injects. Shared so the MCP tool and the hook can
4
+ * never drift into two different projections of the same store.
5
+ */
6
+ export function projectContext(project, entries, total) {
7
+ if (total === 0) {
8
+ return `# Shared context: ${project}\n\n(No entries yet. Use write_context to record the first decision.)`;
9
+ }
10
+ const header = total > entries.length
11
+ ? `# Shared context: ${project}\n\n_Showing the ${entries.length} most recent of ${total} entries._`
12
+ : `# Shared context: ${project}`;
13
+ const body = entries
14
+ .map((e) => `## ${e.type} — ${e.author} — ${e.timestamp}\n\n${e.payload}`)
15
+ .join("\n\n---\n\n");
16
+ return `${header}\n\n${body}`;
17
+ }
18
+ //# sourceMappingURL=context-format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-format.js","sourceRoot":"","sources":["../src/context-format.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAC5B,OAAe,EACf,OAAsB,EACtB,KAAa;IAEb,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QAChB,OAAO,qBAAqB,OAAO,uEAAuE,CAAC;IAC7G,CAAC;IACD,MAAM,MAAM,GACV,KAAK,GAAG,OAAO,CAAC,MAAM;QACpB,CAAC,CAAC,qBAAqB,OAAO,oBAAoB,OAAO,CAAC,MAAM,mBAAmB,KAAK,YAAY;QACpG,CAAC,CAAC,qBAAqB,OAAO,EAAE,CAAC;IACrC,MAAM,IAAI,GAAG,OAAO;SACjB,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,IAAI,MAAM,CAAC,CAAC,MAAM,MAAM,CAAC,CAAC,SAAS,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;SACzE,IAAI,CAAC,aAAa,CAAC,CAAC;IACvB,OAAO,GAAG,MAAM,OAAO,IAAI,EAAE,CAAC;AAChC,CAAC"}