agent-lyra 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +435 -173
  2. package/bin/agent-lyra.js +21 -3
  3. package/bin/lyra-oss-preview.js +14 -0
  4. package/package.json +60 -56
  5. package/src/app-builder/export.js +109 -109
  6. package/src/app-builder/init.js +52 -52
  7. package/src/app-builder/manifest-contract.js +46 -0
  8. package/src/app-builder/preview.js +22 -22
  9. package/src/app-builder/saved-app.js +70 -70
  10. package/src/app-builder/saved-preview-browser.js +33 -33
  11. package/src/app-builder/saved-preview.html +24 -24
  12. package/src/app-builder/saved-preview.js +61 -61
  13. package/src/app-builder/validate.js +21 -64
  14. package/src/coding/catalog.js +56 -0
  15. package/src/coding/cloud-catalog.js +44 -0
  16. package/src/coding/detect-stack.mjs +110 -0
  17. package/src/coding/export.js +130 -0
  18. package/src/coding/setup.js +174 -0
  19. package/src/init.js +32 -4
  20. package/src/memory/cli.js +21 -0
  21. package/src/memory/contract.json +28 -0
  22. package/src/memory/index.d.ts +49 -0
  23. package/src/memory/index.js +259 -0
  24. package/src/memory/lifecycle.js +29 -0
  25. package/src/memory/local-cli.js +34 -0
  26. package/src/memory/proposals.js +84 -0
  27. package/src/memory/skills-cli.js +26 -0
  28. package/src/memory/sync.js +89 -0
  29. package/src/memory/validation.js +25 -0
  30. package/src/runtime/local-cli.js +2 -1
  31. package/src/studio/agent-ui.css +43 -43
  32. package/src/studio/agent-ui.js +32 -32
  33. package/src/studio/browser.js +331 -289
  34. package/src/studio/export.js +80 -79
  35. package/src/studio/index.html +37 -16
  36. package/src/studio/memory-actions.js +37 -0
  37. package/src/studio/memory-panel.js +200 -0
  38. package/src/studio/project.js +216 -190
  39. package/src/studio/pull-agent.js +72 -0
  40. package/src/studio/push.js +54 -0
  41. package/src/studio/python-agent.js +47 -47
  42. package/src/studio/python-agent.py +25 -25
  43. package/src/studio/server.js +143 -102
  44. package/src/studio/session.js +83 -0
  45. package/src/studio/studio.css +10 -7
  46. package/src/studio/sync.js +42 -39
  47. package/src/studio/workflow-sync.js +157 -0
@@ -0,0 +1,110 @@
1
+ import { lstat, readdir, readFile } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+
5
+ const ignored = new Set(["node_modules", "dist", "build", "vendor", "coverage", "__pycache__", "target", "venv"]);
6
+ const signals = {
7
+ react: ["react"], nextjs: ["next"], typescript: ["typescript"], express: ["express"],
8
+ mongodb: ["mongodb", "mongoose"], postgresql: ["pg", "psycopg", "psycopg2", "asyncpg"],
9
+ fastapi: ["fastapi"], playwright: ["playwright", "@playwright/test", "playwright-core"],
10
+ cucumber: ["@cucumber/cucumber", "cucumber", "behave", "pytest-bdd"],
11
+ mysql: ["mysql", "mysql2", "mysqlclient", "pymysql"], redis: ["redis", "ioredis"],
12
+ "react-native": ["react-native"], dbt: ["dbt-core"], spark: ["pyspark"],
13
+ vue: ["vue"], angular: ["@angular/core"], svelte: ["svelte"], django: ["django"],
14
+ };
15
+
16
+ export async function detectStack(root) {
17
+ const projects = new Map();
18
+ let visited = 0;
19
+ let truncated = false;
20
+ async function scan(folder, scope, depth) {
21
+ if (visited >= 400) { truncated = true; return; }
22
+ visited++;
23
+ if (!(await lstat(folder)).isDirectory()) return;
24
+ const entries = await readdir(folder, { withFileTypes: true });
25
+ entries.sort((a, b) => a.name.localeCompare(b.name, "en"));
26
+ const files = new Set(entries.filter(item => item.isFile()).map(item => item.name));
27
+ const add = (technology, file) => {
28
+ const evidence = scope === "." ? file : scope + "/" + file;
29
+ if (!projects.has(scope)) projects.set(scope, new Map());
30
+ const hits = projects.get(scope);
31
+ if (!hits.has(technology)) hits.set(technology, new Set());
32
+ hits.get(technology).add(evidence);
33
+ };
34
+ async function text(name) {
35
+ const path = join(folder, name);
36
+ const stat = await lstat(path);
37
+ if (!stat.isFile() || stat.size > 256_000) return "";
38
+ return (await readFile(path, "utf8")).replace(/^\uFEFF/, "");
39
+ }
40
+ for (const name of files) {
41
+ if (name === "package.json") {
42
+ let pkg;
43
+ try { pkg = JSON.parse(await text(name)); }
44
+ catch (error) { if (error instanceof SyntaxError) continue; throw error; }
45
+ if (!pkg || typeof pkg !== "object" || Array.isArray(pkg)) continue;
46
+ const deps = [pkg.dependencies, pkg.devDependencies, pkg.optionalDependencies];
47
+ if (!pkg.workspaces || pkg.engines?.node) add("node", name);
48
+ for (const [id, names] of Object.entries(signals)) {
49
+ if (names.some(dep => deps.some(section => section && Object.hasOwn(section, dep)))) add(id, name);
50
+ }
51
+ } else if (name === "pyproject.toml" || /^requirements(?:[-.][\w-]+)?\.txt$/.test(name)) {
52
+ add("python", name);
53
+ const content = await text(name);
54
+ for (const [id, names] of Object.entries(signals)) {
55
+ if (names.some(dep => /^[a-z][a-z0-9-]*$/.test(dep) && new RegExp("[\\s'\"]" + dep + "(?=[\\s'\"[=<>!,;~]|$)", "i").test(" " + content))) add(id, name);
56
+ }
57
+ } else if (/^playwright\.config\.[cm]?[jt]s$/.test(name)) add("playwright", name);
58
+ else if (/^cucumber\.(?:[cm]?js|json|ya?ml)$/.test(name)) add("cucumber", name);
59
+ else if (/^(?:Dockerfile(?:\..+)?|(?:docker-)?compose\.ya?ml)$/.test(name)) add("docker", name);
60
+ else if (name === ".gitlab-ci.yml") add("gitlab-ci", name);
61
+ else if (name === "go.mod") add("go", name);
62
+ else if (name === "Cargo.toml") add("rust", name);
63
+ else if (name === "pom.xml" || /^build\.gradle(?:\.kts)?$/.test(name)) {
64
+ const content = await text(name);
65
+ if (/org\.springframework\.boot/.test(content)) add("spring-boot", name);
66
+ if (/com\.android\.(?:application|library)/.test(content)) add("android", name);
67
+ }
68
+ else if (name === "pubspec.yaml" && /^\s*flutter:/m.test(await text(name))) add("flutter", name);
69
+ else if (name === "dbt_project.yml") add("dbt", name);
70
+ else if (name.endsWith(".tf")) add("terraform", name);
71
+ else if (/^kustomization\.ya?ml$/.test(name)) add("kubernetes", name);
72
+ else if (name.endsWith(".csproj")) add("dotnet", name);
73
+ }
74
+ if (entries.some(item => item.name === ".github" && item.isDirectory())) {
75
+ const workflows = join(folder, ".github", "workflows");
76
+ const stat = await lstat(workflows).catch(error => { if (error.code !== "ENOENT") throw error; });
77
+ if (stat?.isDirectory()) {
78
+ const workflow = (await readdir(workflows, { withFileTypes: true })).find(item => item.isFile() && /\.ya?ml$/.test(item.name));
79
+ if (workflow) add("github-actions", ".github/workflows/" + workflow.name);
80
+ }
81
+ }
82
+ const xcode = entries.find(item => item.isDirectory() && item.name.endsWith(".xcodeproj"));
83
+ if (xcode) add("ios", xcode.name);
84
+ // Gherkin is a hint by itself. A project dependency or config identifies Cucumber.
85
+ const feature = [...files].find(name => name.endsWith(".feature"));
86
+ if (feature) add("gherkin", feature);
87
+ for (const child of entries) {
88
+ if (!child.isDirectory() || child.name.startsWith(".") || ignored.has(child.name)) continue;
89
+ if (depth >= 4 || visited >= 400) { truncated = true; continue; }
90
+ await scan(join(folder, child.name), scope === "." ? child.name : scope + "/" + child.name, depth + 1);
91
+ }
92
+ }
93
+ await scan(root, ".", 0);
94
+ return {
95
+ truncated,
96
+ projects: [...projects].map(([scope, hits]) => ({
97
+ scope, technologies: [...hits].map(([id, evidence]) => ({ id, evidence: [...evidence] })),
98
+ })),
99
+ };
100
+ }
101
+
102
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
103
+ const root = resolve(process.argv[2] ?? fileURLToPath(new URL("../../", import.meta.url)));
104
+ try {
105
+ console.log(JSON.stringify(await detectStack(root), null, 2));
106
+ } catch (error) {
107
+ console.error(error.message);
108
+ process.exitCode = 1;
109
+ }
110
+ }
@@ -0,0 +1,130 @@
1
+ import { lstat, readFile, readdir } from "node:fs/promises";
2
+ import { join, resolve } from "node:path";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { parseArgs } from "node:util";
5
+ import { readLocalAgent } from "../studio/project.js";
6
+ import { prepareProjectFiles } from "./setup.js";
7
+
8
+ const formats = {
9
+ claude: { marker: ".claude", skills: ".claude/skills", agents: ".claude/agents", extension: ".md" },
10
+ codex: { marker: ".codex", skills: ".agents/skills", agents: ".codex/agents", extension: ".toml" },
11
+ copilot: { marker: ".github", skills: ".github/skills", agents: ".github/agents", extension: ".agent.md" },
12
+ };
13
+ const safeName = /^[a-z0-9][a-z0-9-]{0,95}$/;
14
+ const missing = error => {
15
+ if (error.code !== "ENOENT") throw error;
16
+ return null;
17
+ };
18
+
19
+ async function entries(path) {
20
+ const stat = await lstat(path).catch(missing);
21
+ if (!stat) return [];
22
+ if (!stat.isDirectory()) throw new Error("Expected a regular project directory: " + path);
23
+ return readdir(path, { withFileTypes: true });
24
+ }
25
+
26
+ async function text(path) {
27
+ const stat = await lstat(path).catch(missing);
28
+ if (!stat?.isFile() || stat.size > 64_000) return "";
29
+ return (await readFile(path, "utf8")).replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
30
+ }
31
+
32
+ function scalar(header, key) {
33
+ const value = new RegExp("^" + key + ":[ \t]*(.+)$", "m").exec(header)?.[1]?.trim();
34
+ if (!value) return "";
35
+ if (!value.startsWith('"')) return value.replace(/^'|'$/g, "");
36
+ try {
37
+ const parsed = JSON.parse(value);
38
+ return typeof parsed === "string" ? parsed : "";
39
+ } catch { return ""; }
40
+ }
41
+
42
+ async function sources(root, output) {
43
+ await entries(join(root, ".lyra"));
44
+ const agents = new Map();
45
+ const skills = new Map();
46
+ const agentDir = join(root, ".lyra", "agents");
47
+ for (const entry of await entries(agentDir)) {
48
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
49
+ const source = await text(join(agentDir, entry.name));
50
+ const item = readLocalAgent(source);
51
+ if (!item || item.source !== "local" || !safeName.test(item.id.slice(6))) {
52
+ output.write("Skip unsupported agent " + JSON.stringify(entry.name) + "\n");
53
+ continue;
54
+ }
55
+ const id = item.id.slice(6);
56
+ if (agents.has(id)) throw new Error("Duplicate Lyra agent ID: " + id);
57
+ agents.set(id, item);
58
+ }
59
+ const skillDir = join(root, ".lyra", "skills");
60
+ for (const entry of await entries(skillDir)) {
61
+ if (!entry.isDirectory() || !safeName.test(entry.name)) continue;
62
+ const source = await text(join(skillDir, entry.name, "SKILL.md"));
63
+ const front = /^---\n([\s\S]*?)\n---\n/.exec(source);
64
+ const name = front && scalar(front[1], "name");
65
+ const description = front && scalar(front[1], "description");
66
+ if (!name || name !== entry.name || !description) {
67
+ output.write("Skip skill without matching name and description " + JSON.stringify(entry.name) + "\n");
68
+ continue;
69
+ }
70
+ skills.set(name, ["---", "name: " + name, "description: " + JSON.stringify(description), "---", source.slice(front[0].length)].join("\n"));
71
+ }
72
+ return { agents, skills };
73
+ }
74
+
75
+ function renderAgent(target, id, agent) {
76
+ const description = "AgentLyra project profile for " + agent.name + ".";
77
+ if (target === "codex") {
78
+ const quoted = value => JSON.stringify(value).replace(/\u007f/g, "\\u007F");
79
+ return "name = " + quoted(id) + "\ndescription = " + quoted(description) +
80
+ "\ndeveloper_instructions = " + quoted(agent.prompt) + "\n";
81
+ }
82
+ return ["---", "name: " + id, "description: " + JSON.stringify(description), "---", "", agent.prompt, ""].join("\n");
83
+ }
84
+
85
+ export async function runCodingExport(args, { input = process.stdin, output = process.stdout, root = process.cwd() } = {}) {
86
+ const { values } = parseArgs({ args, options: {
87
+ to: { type: "string" }, dir: { type: "string" }, preview: { type: "boolean" },
88
+ yes: { type: "boolean", short: "y" }, help: { type: "boolean", short: "h" },
89
+ } });
90
+ if (values.help) {
91
+ output.write("Usage: agent-lyra setup coding export [--to claude,codex,copilot] [--preview | --yes] [--dir <folder>]\n");
92
+ return;
93
+ }
94
+ if (!input.isTTY && (!values.to || (!values.preview && !values.yes))) {
95
+ throw new Error("Provide --to with --preview or --yes when running without an interactive terminal.");
96
+ }
97
+ const project = resolve(root, values.dir ?? ".");
98
+ const rl = input.isTTY ? createInterface({ input, output }) : null;
99
+ try {
100
+ let choice = values.to;
101
+ if (!choice) {
102
+ const existing = new Set((await entries(project)).filter(item => item.isDirectory() || item.isFile()).map(item => item.name));
103
+ const hints = Object.entries(formats).filter(([id, { marker }]) => existing.has(marker) ||
104
+ (id === "codex" && existing.has(".agents")) || (id === "claude" && existing.has("CLAUDE.md")));
105
+ if (hints.length) output.write("Project files suggest: " + hints.map(([id]) => id).join(", ") + "\n");
106
+ choice = (await rl.question("Export to claude, codex, or copilot (comma separated, Enter to cancel): ")).trim();
107
+ if (!choice) return;
108
+ }
109
+ const targets = [...new Set(choice.split(",").map(name => name.trim().toLowerCase()))];
110
+ if (targets.some(target => !Object.hasOwn(formats, target))) throw new Error("Choose claude, codex, or copilot.");
111
+ const { agents, skills } = await sources(project, output);
112
+ const files = new Map();
113
+ for (const target of targets) {
114
+ const format = formats[target];
115
+ for (const [id, agent] of agents) files.set(format.agents + "/" + id + format.extension, renderAgent(target, id, agent));
116
+ for (const [name, skill] of skills) files.set(format.skills + "/" + name + "/SKILL.md", skill);
117
+ }
118
+ if (!files.size) {
119
+ output.write("No exportable Markdown agents or skills found in .lyra. Run setup coding first.\n");
120
+ return;
121
+ }
122
+ output.write("Export includes instructions only. Tool permissions, hooks, scripts, and other skill resources stay in their original project files.\n");
123
+ const apply = await prepareProjectFiles(project, files, output);
124
+ if (values.preview || (!values.yes && !/^y(?:es)?$/i.test((await rl.question("Write these exports? [y/N] ")).trim()))) return;
125
+ await apply();
126
+ output.write("Assistant export complete. Existing files were preserved.\n");
127
+ } finally {
128
+ rl?.close();
129
+ }
130
+ }
@@ -0,0 +1,174 @@
1
+ import { createHash } from "node:crypto";
2
+ import { detectStack } from "./detect-stack.mjs";
3
+ import { lstat, mkdir, readFile, writeFile } from "node:fs/promises";
4
+ import { join, resolve } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { parseArgs } from "node:util";
7
+ import { areas } from "./catalog.js";
8
+ import { bundledCatalog, fetchCodingCatalog } from "./cloud-catalog.js";
9
+ const areaLabels = { frontend: "Frontend", backend: "Backend and APIs", database: "Databases", devops: "DevOps", qa: "QA and test automation", mobile: "Mobile", data: "Data engineering" };
10
+
11
+ function showChoices(output, { presets, technologies }) {
12
+ output.write("Presets: " + Object.keys(presets).join(", ") + "\n");
13
+ for (const [area, label] of Object.entries(areaLabels)) {
14
+ output.write(label + ": " + Object.entries(technologies).filter(([, pack]) => pack[0] === area)
15
+ .map(([id, [, name]]) => name + " (" + id + ")").join(", ") + "\n");
16
+ }
17
+ }
18
+
19
+ export async function selectCodingStack(rl, output, catalog = bundledCatalog) {
20
+ showChoices(output, catalog);
21
+ return (await rl.question("Choose presets or technologies (comma separated, Enter to skip): ")).trim();
22
+ }
23
+
24
+ function plan(selection, scope, { version, technologies, presets }) {
25
+ const chosen = selection.toLowerCase().split(",").map(part => part.trim()).filter(Boolean);
26
+ if (!chosen.length) throw new Error("Choose at least one preset or technology.");
27
+ const ids = [...new Set(chosen.flatMap(id => {
28
+ if (Object.hasOwn(presets, id)) return presets[id];
29
+ if (Object.hasOwn(technologies, id)) return [id];
30
+ throw new Error("Unknown technology or preset: " + id);
31
+ }))].sort();
32
+ const files = new Map();
33
+ for (const id of ids) {
34
+ const [, name, title, instructions] = technologies[id];
35
+ files.set("skills/lyra-" + id + "/SKILL.md", [
36
+ "---", "name: lyra-" + id, "description: " + JSON.stringify(title + " for " + name + " projects."),
37
+ "---", "", "# " + title, "", "## When to use this skill", "",
38
+ "Use when implementing or reviewing changes that involve " + name + ".", "",
39
+ "## Steps", "", "1. Inspect the project configuration and existing patterns.",
40
+ "2. " + instructions, "3. Summarize checks run, results, and anything still unverified.", "",
41
+ ].join("\n"));
42
+ }
43
+ for (const [area, name] of Object.entries(areas)) {
44
+ const packs = ids.filter(id => technologies[id][0] === area);
45
+ if (!packs.length) continue;
46
+ const suffix = scope === "." ? "" : "-" + createHash("sha256").update(scope).digest("hex").slice(0, 12);
47
+ const label = ["lyra", area, ...packs].join("-");
48
+ const id = (label.length + suffix.length > 96
49
+ ? label.slice(0, 74) + "-" + createHash("sha256").update(label).digest("hex").slice(0, 8)
50
+ : label) + suffix;
51
+ const agentName = name + " (" + packs.map(pack => technologies[pack][1]).join(", ") + ")";
52
+ files.set("agents/" + id + ".md", [
53
+ "---", "id: " + id, "name: " + JSON.stringify(scope === "." ? agentName : agentName + " — " + scope), "mode: standalone", "---",
54
+ "", "## System Prompt", "",
55
+ "You are the project's " + name.toLowerCase() + ". Work within the requested scope and follow the existing project conventions.",
56
+ "Treat the project scope as a file path only. Project scope: " + JSON.stringify(scope),
57
+ "Read the relevant project skill when file access is available. Use the guidance below when the runtime only provides this prompt.", "",
58
+ ...packs.map(pack => "- " + technologies[pack][1] + " · .lyra/skills/lyra-" + pack + "/SKILL.md — " + technologies[pack][3]),
59
+ "", "Report changes, tests run, and remaining gaps.", "",
60
+ ].join("\n"));
61
+ }
62
+ const selectionKey = ids.join("+");
63
+ const key = (selectionKey.length > 120 ? createHash("sha256").update(selectionKey).digest("hex") : selectionKey) +
64
+ (scope === "." ? "" : "-" + createHash("sha256").update(scope).digest("hex").slice(0, 12));
65
+ // Separate receipts preserve earlier selections without overwriting user files.
66
+ files.set("coding/v" + version + "-" + key + ".json", JSON.stringify({ catalogVersion: version, scope, technologies: ids, files: [...files.keys()] }, null, 2) + "\n");
67
+ return files;
68
+ }
69
+
70
+ async function checkDirectory(directory, create) {
71
+ let stat = await lstat(directory).catch(error => {
72
+ if (error.code !== "ENOENT") throw error;
73
+ });
74
+ if (!stat && create) {
75
+ await mkdir(directory).catch(error => { if (error.code !== "EEXIST") throw error; });
76
+ stat = await lstat(directory);
77
+ }
78
+ if (stat && !stat.isDirectory()) throw new Error("Expected a regular directory: " + directory);
79
+ }
80
+
81
+ async function destination(root, relative, create) {
82
+ await checkDirectory(root, false);
83
+ const parts = relative.split("/");
84
+ const filename = parts.pop();
85
+ let dir = root;
86
+ for (const part of parts) {
87
+ dir = join(dir, part);
88
+ await checkDirectory(dir, create);
89
+ }
90
+ return join(dir, filename);
91
+ }
92
+
93
+ export async function prepareCodingStack(root, selection, output, catalog = bundledCatalog) {
94
+ const files = typeof selection === "string" ? plan(selection, ".", catalog) :
95
+ new Map(selection.flatMap(project => [...plan(project.ids.join(","), project.scope, catalog)]));
96
+ files.set("scripts/detect-stack.mjs", await readFile(new URL("./detect-stack.mjs", import.meta.url), "utf8"));
97
+ return prepareProjectFiles(root, new Map([...files].map(([name, content]) => [".lyra/" + name, content])), output);
98
+ }
99
+
100
+ export async function prepareProjectFiles(root, files, output) {
101
+ for (const [relative, content] of files) {
102
+ const path = await destination(root, relative, false);
103
+ const stat = await lstat(path).catch(error => {
104
+ if (error.code !== "ENOENT") throw error;
105
+ });
106
+ const unchanged = stat?.isFile() && (await readFile(path, "utf8")).replace(/\r\n/g, "\n") === content;
107
+ output.write((!stat ? "Create" : unchanged ? "Already installed" : "Keep existing") + " " + relative + "\n");
108
+ }
109
+ return async () => {
110
+ for (const [relative, content] of files) {
111
+ const path = await destination(root, relative, true);
112
+ await writeFile(path, content, { flag: "wx" }).catch(error => {
113
+ if (error.code !== "EEXIST" && error.code !== "EISDIR") throw error;
114
+ });
115
+ }
116
+ };
117
+ }
118
+
119
+ export async function recommendCodingStacks(root, output, { technologies } = bundledCatalog) {
120
+ const detected = await detectStack(root);
121
+ if (detected.truncated) output.write("Scan limit reached. Some folders were skipped.\n");
122
+ const selected = [];
123
+ for (const { scope, technologies: hits } of detected.projects) {
124
+ const supported = hits.filter(({ id }) => Object.hasOwn(technologies, id));
125
+ output.write("Project " + JSON.stringify(scope) + "\n");
126
+ for (const { id, evidence } of hits) {
127
+ output.write(" " + id + (Object.hasOwn(technologies, id) ? "" : " (no pack)") +
128
+ " · " + evidence.map(file => JSON.stringify(file)).join(", ") + "\n");
129
+ }
130
+ if (supported.length) selected.push({ scope, ids: supported.map(hit => hit.id) });
131
+ }
132
+ if (!selected.length) output.write("No supported stack detected. Choose your technologies manually.\n");
133
+ return selected;
134
+ }
135
+
136
+ export async function runCodingSetup(args, { input = process.stdin, output = process.stdout, root = process.cwd() } = {}) {
137
+ const { values } = parseArgs({ args, options: {
138
+ "catalog-version": { type: "string" }, detect: { type: "boolean" }, stack: { type: "string" }, dir: { type: "string" }, preview: { type: "boolean" },
139
+ yes: { type: "boolean", short: "y" }, help: { type: "boolean", short: "h" },
140
+ } });
141
+ if (values.help) {
142
+ output.write("Usage: agent-lyra setup coding [--stack <names> | --detect] [--catalog-version <number>] [--preview | --yes] [--dir <folder>]\n");
143
+ return;
144
+ }
145
+ if (values.detect && values.stack) throw new Error("Choose --detect or --stack.");
146
+ if (!input.isTTY && ((!values.stack && !values.detect) || (!values.preview && !values.yes))) {
147
+ throw new Error("Provide --stack or --detect with --preview or --yes when running without an interactive terminal.");
148
+ }
149
+ const rl = input.isTTY ? createInterface({ input, output }) : null;
150
+ try {
151
+ const target = resolve(root, values.dir ?? ".");
152
+ const catalog = values["catalog-version"] ? await fetchCodingCatalog(values["catalog-version"]) : bundledCatalog;
153
+ output.write("Coding catalog " + catalog.version + (values["catalog-version"] ? " (Cloud)" : " (bundled)") + "\n");
154
+ const useDetection = values.detect || (!values.stack && /^y(?:es)?$/i.test((await rl.question("Detect technologies from this project? [y/N] ")).trim()));
155
+ let selected = values.stack;
156
+ if (useDetection) {
157
+ selected = await recommendCodingStacks(target, output, catalog);
158
+ if (!selected.length) {
159
+ selected = undefined;
160
+ } else if (rl && !values.yes && !values.preview) {
161
+ const answer = (await rl.question("Use these recommendations? [Y/n] ")).trim();
162
+ if (/^n(?:o)?$/i.test(answer)) selected = undefined;
163
+ }
164
+ }
165
+ if (selected === undefined && rl && !values.preview) selected = await selectCodingStack(rl, output, catalog);
166
+ if (!selected) return;
167
+ const apply = await prepareCodingStack(target, selected, output, catalog);
168
+ if (values.preview || (!values.yes && !/^y(?:es)?$/i.test((await rl.question("Create these files? [y/N] ")).trim()))) return;
169
+ await apply();
170
+ output.write("Coding setup complete. Edit your agent and skill guidance in .lyra.\n");
171
+ } finally {
172
+ rl?.close();
173
+ }
174
+ }
package/src/init.js CHANGED
@@ -6,6 +6,8 @@ import { emitKeypressEvents } from "node:readline";
6
6
  import { stdin as input, stdout as output } from "node:process";
7
7
  import { GATED_DOMAINS, STANDALONE_DOMAINS, getDomainCatalog } from "./catalog.js";
8
8
 
9
+ import { prepareCodingStack, recommendCodingStacks, selectCodingStack } from "./coding/setup.js";
10
+
9
11
  const DEFAULT_API_BASE_URL = "https://www.agentlyra.in";
10
12
 
11
13
  function parseArgs(argv = process.argv.slice(2)) {
@@ -40,7 +42,7 @@ function parseArgs(argv = process.argv.slice(2)) {
40
42
  }
41
43
 
42
44
  function printUsage() {
43
- output.write(`Usage:\n agent-lyra init\n lyra init\n\nOptions:\n --mode standalone|gated\n --domains coding,finance\n --api-key <key>\n --api-base-url <url>\n --dir <target-directory>\n --force\n`);
45
+ output.write(`Usage:\n agent-lyra init\n lyra init\n\nOptions:\n --mode standalone|gated\n --domains coding,finance\n --stack mern,playwright\n --detect\n --api-key <key>\n --api-base-url <url>\n --dir <target-directory>\n --force\n`);
44
46
  }
45
47
 
46
48
  function printWelcomeBanner() {
@@ -800,9 +802,10 @@ export async function runInitWizard(options = {}) {
800
802
 
801
803
  try {
802
804
  printWelcomeBanner();
803
- const wantsLogin = await askYesNo(rl, "Do you want to login with a Lyra API key now?", false);
805
+ const stackMode = (options.stack || options.detect) && ["standalone", "gated"].includes(options.mode);
806
+ const wantsLogin = !stackMode && await askYesNo(rl, "Do you want to login with a Lyra API key now?", false);
804
807
  const apiBaseUrl = options["api-base-url"] || process.env.LYRA_API_BASE_URL || DEFAULT_API_BASE_URL;
805
- let apiKey = options["api-key"] || process.env.LYRA_API_KEY || "";
808
+ let apiKey = stackMode && options.mode === "standalone" ? "" : options["api-key"] || process.env.LYRA_API_KEY || "";
806
809
  let importedAgents = [];
807
810
 
808
811
  if (wantsLogin && !apiKey) {
@@ -820,7 +823,7 @@ export async function runInitWizard(options = {}) {
820
823
  }
821
824
  }
822
825
 
823
- const chosenGroup = await chooseFlowGroup(rl);
826
+ const chosenGroup = stackMode ? undefined : await chooseFlowGroup(rl);
824
827
  let mode = options.mode;
825
828
  if (mode !== "standalone" && mode !== "gated") {
826
829
  mode = chosenGroup === "everyday" ? "gated" : await chooseMode(rl, mode);
@@ -847,6 +850,7 @@ export async function runInitWizard(options = {}) {
847
850
  options: catalogWithHints,
848
851
  });
849
852
 
853
+ if (stackMode && !presetDomains.length) throw new Error("Use --domains with a valid Coding or Engineering domain ID.");
850
854
  const selected = presetDomains.length > 0
851
855
  ? presetDomains
852
856
  : await selectManyGrouped(
@@ -908,8 +912,32 @@ export async function runInitWizard(options = {}) {
908
912
 
909
913
  const targetDir = path.resolve(options.dir || process.cwd());
910
914
  const lyraDir = path.join(targetDir, ".lyra");
915
+ const coding = selectedDomains.some(domain => domain.id === "coding" || domain.id === "engineering-bootstrap");
916
+ if (options.stack !== undefined && (!coding || typeof options.stack !== "string")) {
917
+ throw new Error("Use --stack with a stack name and the Coding domain.");
918
+ }
919
+ if (options.detect && (!coding || options.stack)) throw new Error("Use --detect with the Coding domain instead of --stack.");
920
+ let stack = options.stack;
921
+ if (coding && !stack) {
922
+ const detect = options.detect || (input.isTTY && await askYesNo(rl, "Detect technologies from this project?", false));
923
+ if (detect) {
924
+ const recommendations = await recommendCodingStacks(targetDir, output);
925
+ if (recommendations.length && (options.detect || await askYesNo(rl, "Use these recommendations?", true))) stack = recommendations;
926
+ }
927
+ if (!stack && input.isTTY) stack = await selectCodingStack(rl, output);
928
+ }
929
+ let applyCoding;
930
+ if (coding) {
931
+ const existing = await fs.lstat(lyraDir).catch(error => {
932
+ if (error.code !== "ENOENT") throw error;
933
+ });
934
+ if (existing) throw new Error("This project already has .lyra. Run agent-lyra setup coding to add packs while keeping your files.");
935
+ const apply = await prepareCodingStack(targetDir, stack || [], output);
936
+ if (!stack || options.stack || options.detect || /^y(?:es)?$/i.test(await askQuestion(rl, "Create these coding files? [y/N] "))) applyCoding = apply;
937
+ }
911
938
  await ensureEmptyOrApproved(rl, lyraDir, Boolean(options.force));
912
939
  await writeScaffold({ targetDir, mode, selectedDomains, apiKey });
940
+ if (applyCoding) await applyCoding();
913
941
 
914
942
  output.write(`Created ${lyraDir} for ${mode} mode with ${selectedDomains.length} domain(s).\n`);
915
943
  } finally {
@@ -0,0 +1,21 @@
1
+ import { syncMemory } from "./sync.js";
2
+ import { runLocalMemory } from "./local-cli.js";
3
+ export async function runMemory(args, output = process.stdout) {
4
+ if (args[0] === "cloud") return runCloudMemory(args.slice(1), output);
5
+ if (!args[0] || args[0] === "--help") { await runLocalMemory(args, output); output.write("Cloud: agent-lyra memory cloud --help\n"); return; }
6
+ return runLocalMemory(args, output);
7
+ }
8
+
9
+ async function runCloudMemory(args, output) {
10
+ const [action, id, flag] = args;
11
+ if (!action || action === "--help") {
12
+ output.write("Usage: agent-lyra memory cloud list [cursor] | preview <id> | push <id> --yes | pull <id>\n");
13
+ return;
14
+ }
15
+ const valid = (action === "list" && args.length <= 2) ||
16
+ (["preview", "pull"].includes(action) && args.length === 2) ||
17
+ (action === "push" && args.length === 3 && flag === "--yes");
18
+ if (!valid) throw new Error("See agent-lyra memory cloud --help.");
19
+ const result = await syncMemory(process.cwd(), action, id, { confirmed: flag === "--yes" });
20
+ output.write(JSON.stringify(result, null, 2) + "\n");
21
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "version": 4,
3
+ "applicationId": 1279873601,
4
+ "types": [
5
+ "episodic",
6
+ "semantic",
7
+ "procedural",
8
+ "corrective"
9
+ ],
10
+ "statuses": [
11
+ "candidate",
12
+ "verified",
13
+ "archived"
14
+ ],
15
+ "limits": {
16
+ "records": 5000,
17
+ "results": 100,
18
+ "title": 160,
19
+ "learning": 4000,
20
+ "evidence": 16,
21
+ "id": 128
22
+ },
23
+ "adapters": {"coding":{"types":["corrective"],"prefix":"test:","check":"test","error":"Verification requires a linked passing coding test, a compatibility context, and explicit review."},"practice":{"types":["corrective","procedural"],"prefix":"exercise:","check":"exercise","error":"Verification requires a linked passing practice exercise, a compatibility context, and explicit review."}},
24
+ "migration4": "CREATE TABLE memory_cloud_links (id TEXT PRIMARY KEY, cloud_revision INTEGER NOT NULL, local_revision INTEGER NOT NULL, cloud_account TEXT NOT NULL);",
25
+ "migration3": "CREATE TABLE skill_proposals (id TEXT PRIMARY KEY, context TEXT NOT NULL, title TEXT NOT NULL, markdown TEXT NOT NULL, sources TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','approved','rejected','withdrawn')), created_at TEXT NOT NULL, decided_at TEXT, receipt TEXT);",
26
+ "migration2": "ALTER TABLE memories ADD COLUMN verification TEXT; CREATE INDEX memories_verified ON memories(status, updated_at);",
27
+ "migration": "CREATE TABLE memories (\n id TEXT PRIMARY KEY,\n type TEXT NOT NULL,\n title TEXT NOT NULL,\n learning TEXT NOT NULL,\n evidence TEXT NOT NULL,\n scope TEXT NOT NULL DEFAULT 'project' CHECK (scope = 'project'),\n status TEXT NOT NULL DEFAULT 'candidate',\n revision INTEGER NOT NULL DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n);\nCREATE TABLE memory_tombstones (id TEXT PRIMARY KEY, revision INTEGER NOT NULL, deleted_at TEXT NOT NULL);\nCREATE TABLE memory_index_state (id INTEGER PRIMARY KEY CHECK (id = 1), revision INTEGER NOT NULL, indexed_revision INTEGER NOT NULL);\nINSERT INTO memory_index_state VALUES (1, 0, -1);\nCREATE INDEX memories_status_updated ON memories (status, updated_at DESC);"
28
+ }
@@ -0,0 +1,49 @@
1
+ export type MemoryType = "episodic" | "semantic" | "procedural" | "corrective";
2
+ export type MemoryStatus = "candidate" | "verified" | "archived";
3
+ export interface MemoryInput { type: MemoryType; title: string; learning: string; evidence?: string[] }
4
+ export type MemoryAdapter = "coding" | "practice";
5
+ export type VerificationReceipt = { evidenceId: string; context: string } & (
6
+ { adapter: "coding"; test: string } | { adapter: "practice"; exercise: string }
7
+ );
8
+ export interface MemoryRecord extends MemoryInput {
9
+ id: string;
10
+ evidence: string[];
11
+ scope: "project";
12
+ status: MemoryStatus;
13
+ revision: number;
14
+ createdAt: string;
15
+ updatedAt: string;
16
+ verification?: VerificationReceipt;
17
+ }
18
+ export interface SkillProposalSource { id: string; revision: number; evidenceId: string }
19
+ export interface SkillProposalReceipt { evidenceId: string; context: string; result: "passed"; reviewed: true }
20
+ export interface SkillProposal {
21
+ id: string;
22
+ context: string;
23
+ title: string;
24
+ markdown: string;
25
+ sources: SkillProposalSource[];
26
+ status: "pending" | "approved" | "rejected" | "withdrawn";
27
+ createdAt: string;
28
+ decidedAt: string | null;
29
+ receipt: SkillProposalReceipt | null;
30
+ }
31
+ export interface MemoryStore {
32
+ readonly file: string;
33
+ consolidate(context: string): Array<{ title: string; learning: string; sources: SkillProposalSource[] }>;
34
+ propose(context: string, memoryId: string): SkillProposal;
35
+ proposal(id: string): SkillProposal | null;
36
+ proposals(): SkillProposal[];
37
+ decideProposal(id: string, decision: "approved" | "rejected" | "withdrawn", evidence?: SkillProposalReceipt): SkillProposal;
38
+ close(): void;
39
+ get(id: string): MemoryRecord | null;
40
+ list(limit?: number): MemoryRecord[];
41
+ record(value: MemoryInput): MemoryRecord;
42
+ search(query: string, limit?: number): MemoryRecord[];
43
+ stats(): { schemaVersion: number; search: "fts5" | "keyword" } & Record<MemoryStatus, number>;
44
+ verify(id: string, evidence: VerificationReceipt & { result: "passed"; reviewed: true }): MemoryRecord;
45
+ retrieve(query: string, context: string, adapter?: MemoryAdapter): MemoryRecord[];
46
+ archive(id: string): MemoryRecord | null;
47
+ forget(id: string): boolean;
48
+ }
49
+ export function openMemoryStore(root?: string, options?: { forceKeyword?: boolean }): Promise<MemoryStore>;