-
Notifications
You must be signed in to change notification settings - Fork 352
feat(memory): restore read-only file controls #3616
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sarahwooders
wants to merge
2
commits into
main
Choose a base branch
from
letta/restore-memory-read-only-7db6b057
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import { describe, expect, it } from "bun:\u0074est"; | ||
| import { checkPermission } from "@/permissions/checker"; | ||
| import type { PermissionRules } from "@/permissions/types"; | ||
| import { updateReadOnlyFrontmatter } from "./memory-read-only"; | ||
|
|
||
| const permissions: PermissionRules = { | ||
| allow: [], | ||
| deny: [], | ||
| ask: [], | ||
| alwaysAsk: [], | ||
| additionalDirectories: [], | ||
| }; | ||
|
|
||
| describe("memory read-only", () => { | ||
| it("adds and toggles read_only without changing the body", () => { | ||
| const original = "---\ndescription: Keep\n---\n\nBody\n"; | ||
| const enabled = updateReadOnlyFrontmatter(original, true); | ||
| expect(enabled).toBe( | ||
| "---\ndescription: Keep\nread_only: true\n---\n\nBody\n", | ||
| ); | ||
| expect(updateReadOnlyFrontmatter(enabled ?? "", false)).toContain( | ||
| "read_only: false\n---\n\nBody\n", | ||
| ); | ||
| expect( | ||
| updateReadOnlyFrontmatter("---\r\ndescription: CRLF\r\n---\r\n", true), | ||
| ).toContain("read_only: true\r\n---"); | ||
| }); | ||
|
|
||
| it("always requires approval", () => { | ||
| for (const command of [ | ||
| "letta memory read-only system/persona.md true", | ||
| `sh -c "letta memfs read-only reference/policy.md false"`, | ||
| ]) { | ||
| expect(checkPermission("Bash", { command }, permissions).decision).toBe( | ||
| "alwaysAsk", | ||
| ); | ||
| } | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; | ||
| import { isAbsolute, relative, resolve } from "node:path"; | ||
| import { | ||
| assertMemoryRepoCleanForWrite, | ||
| commitMemoryWrite, | ||
| } from "@/agent/memory-git"; | ||
| import { isLocalBackendEnvEnabled } from "@/backend/local/paths"; | ||
|
|
||
| export function updateReadOnlyFrontmatter( | ||
| content: string, | ||
| value: boolean, | ||
| ): string | null { | ||
| const frontmatter = /^---\r?\n[\s\S]*?\r?\n---/.exec(content); | ||
| if (!frontmatter) throw new Error("Memory file is missing frontmatter."); | ||
|
|
||
| const field = /^read_only\s*:\s*(.*?)\s*$/m.exec(frontmatter[0]); | ||
| if (field && field[1] !== "true" && field[1] !== "false") { | ||
| throw new Error("Memory file read_only must be true or false."); | ||
| } | ||
| if (field?.[1] === String(value)) return null; | ||
| if (field) { | ||
| return content.replace( | ||
| /^read_only\s*:\s*(?:true|false)\s*$/m, | ||
| `read_only: ${value}`, | ||
| ); | ||
| } | ||
|
|
||
| const newline = frontmatter[0].includes("\r\n") ? "\r\n" : "\n"; | ||
| const closing = frontmatter.index + frontmatter[0].length - 3; | ||
| return `${content.slice(0, closing)}read_only: ${value}${newline}${content.slice(closing)}`; | ||
| } | ||
|
|
||
| function resolveMemoryFile(memoryDir: string, input: string) { | ||
| if (isAbsolute(input)) throw new Error("Memory path must be relative."); | ||
| const absolutePath = resolve(memoryDir, input); | ||
| const relativePath = relative(memoryDir, absolutePath).replace(/\\/g, "/"); | ||
| if (!/^(system|reference)\/.+\.md$/.test(relativePath)) { | ||
| throw new Error( | ||
| "Memory path must be a .md file under system/ or reference/.", | ||
| ); | ||
| } | ||
| if (!existsSync(absolutePath)) | ||
| throw new Error(`Memory file not found: ${input}`); | ||
| if ( | ||
| relative(realpathSync(memoryDir), realpathSync(absolutePath)).startsWith( | ||
| "..", | ||
| ) | ||
| ) { | ||
| throw new Error("Memory file resolves outside the memory directory."); | ||
| } | ||
| return { absolutePath, relativePath }; | ||
| } | ||
|
|
||
| export async function runMemoryReadOnlyAction(args: { | ||
| agentId: string; | ||
| memoryDir: string; | ||
| path?: string; | ||
| value?: string; | ||
| extraPositionals: string[]; | ||
| }): Promise<number> { | ||
| if (!args.path || !args.value || args.extraPositionals.length) { | ||
| console.error("Usage: letta memory read-only <path> <true|false>"); | ||
| return 1; | ||
| } | ||
| if (args.value !== "true" && args.value !== "false") { | ||
| console.error("read-only value must be true or false."); | ||
| return 1; | ||
| } | ||
|
|
||
| await assertMemoryRepoCleanForWrite(args.memoryDir); | ||
| const file = resolveMemoryFile(args.memoryDir, args.path); | ||
| const original = readFileSync(file.absolutePath, "utf8"); | ||
| const desired = args.value === "true"; | ||
| const updated = updateReadOnlyFrontmatter(original, desired); | ||
| if (updated === null) return 0; | ||
|
|
||
| writeFileSync(file.absolutePath, updated, "utf8"); | ||
| const previousApproval = process.env.LETTA_APPROVED_READ_ONLY_CHANGE; | ||
| process.env.LETTA_APPROVED_READ_ONLY_CHANGE = "1"; | ||
| try { | ||
| const result = await commitMemoryWrite({ | ||
| memoryDir: args.memoryDir, | ||
| pathspecs: [file.relativePath], | ||
| reason: `${desired ? "Mark" : "Unmark"} ${file.relativePath} as read-only`, | ||
| author: { | ||
| agentId: args.agentId, | ||
| authorName: args.agentId, | ||
| authorEmail: `${args.agentId}@letta.com`, | ||
| }, | ||
| syncMode: isLocalBackendEnvEnabled() ? "local" : "remote", | ||
| }); | ||
| if (!result.committed) { | ||
| writeFileSync(file.absolutePath, original, "utf8"); | ||
| return 1; | ||
| } | ||
| console.log( | ||
| JSON.stringify({ ...result, path: file.relativePath, readOnly: desired }), | ||
| ); | ||
| return 0; | ||
| } catch (error) { | ||
| writeFileSync(file.absolutePath, original, "utf8"); | ||
| throw error; | ||
| } finally { | ||
| if (previousApproval === undefined) | ||
| delete process.env.LETTA_APPROVED_READ_ONLY_CHANGE; | ||
| else process.env.LETTA_APPROVED_READ_ONLY_CHANGE = previousApproval; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import type { PermissionCheckResult } from "./types"; | ||
|
|
||
| type ToolArgs = Record<string, unknown>; | ||
|
|
||
| export function envFlagEnabled(name: string): boolean { | ||
| const value = process.env[name]; | ||
| if (!value) return false; | ||
| return value === "1" || value.toLowerCase() === "true"; | ||
| } | ||
|
|
||
| function extractShellCommand(toolArgs: ToolArgs): string | null { | ||
| const command = | ||
| typeof toolArgs.cmd === "string" ? toolArgs.cmd : toolArgs.command; | ||
| if (typeof command === "string") return command; | ||
| return Array.isArray(command) ? command.join(" ") : null; | ||
| } | ||
|
|
||
| export function getMandatoryApproval( | ||
| canonicalTool: string, | ||
| toolArgs: ToolArgs, | ||
| ): PermissionCheckResult | null { | ||
| if (canonicalTool !== "Bash") return null; | ||
| const command = extractShellCommand(toolArgs); | ||
| if ( | ||
| !command || | ||
| /(?:^|[\s;&|'"])(?:[^\s;&|]*\/)?letta(?:\.js)?['"]?\s+(?:memory|memfs)\s+read-only(?:\s|$)/.exec( | ||
| command, | ||
| ) === null | ||
| ) { | ||
| return null; | ||
| } | ||
| return { | ||
| decision: "alwaysAsk", | ||
| matchedRule: "Bash(letta memory read-only:*)", | ||
| reason: "Changing memory read-only status requires explicit user approval", | ||
| }; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
alwaysAskgate only matchesletta memory read-onlyin the command string, but the pre-commit hook bypass is the env varLETTA_APPROVED_READ_ONLY_CHANGE=1. An agent in unrestricted mode can edit a read-only file then runLETTA_APPROVED_READ_ONLY_CHANGE=1 git commit -m "..."to bypass both this permission check and the pre-commit hook.