diff --git a/CLAUDE.md b/CLAUDE.md index 4dbd274..5678b03 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,7 +39,8 @@ Each row names the doc first, then the code that proves it. Read the doc before - Profiles, states, the plan, short names, the profile file: `docs/profiles.md`; `src/core/installer/`, `src/core/loader/states.ts`. - Writing an extension, `ctx`, peers, author commands, `extension create`, run it locally: - `docs/extensions.md`; `src/extension.ts`, `src/core/loader/`, `src/commands/extension/create.ts`, + `docs/extensions.md`; `src/extension.ts`, `src/core/loader/`, `src/commands/extension/create.ts` + (the template source: `create-source.ts`), `up.ts`. - e2e scenarios: `e2e/core/README.md`. Test fixtures: `fixtures/README.md`. - CI jobs and coverage floors (no doc): `.github/workflows/ci.yml`, `vitest.config.ts`. diff --git a/docs/extensions.md b/docs/extensions.md index da065aa..36d4a93 100644 --- a/docs/extensions.md +++ b/docs/extensions.md @@ -306,8 +306,11 @@ parts, `create` sets `MIN_EXECUTED` to 1. `MIN_EXECUTED` is the least number of must run. After the first green run, set it to the real count. When `create` cannot find that line, it says so and you set it by hand. -`--from ` takes another template repo, and `--from ` one of its -branches. For any source other than `agentage/extension-template` itself, `create` first prints +The template is the folder `template/` of the kit repo (`agentage/platform:template`); only that +folder is copied, with no history. `--from ` takes another template repo at its root +(`agentage/extension-template` is the old template), `--from ` one of its +branches, and `:folder` after either one folder of it. For any source other than the kit's +`template` folder or `agentage/extension-template`, `create` first prints that code from that repo will be built and run on this machine, and asks `run it? (y/N)`; with `--yes` it does not ask, and with no terminal (or `--json`) it needs `--yes`. After the clone, `create` runs `npm ci --ignore-scripts`, builds the package (as `extension build` does) and gives @@ -316,7 +319,7 @@ the clone, the rename and the parts dropped, no npm and no build. `create` adds folder's `.gitignore` when it is missing, and says so. It ends with `url `. -1. Install git and npm for `create`, which clones the template from GitHub. `build --container`, +1. Install git and npm for `create`, which clones the kit repo from GitHub. `build --container`, `build --push`, `up --docker` and `release` also need Docker and a committed tree. 2. Inside the extension folder, run `npx agentage extension up`. Use `npx agentage`, not the global `agentage`, which can be older than the version the project pins. It builds the diff --git a/docs/reference.md b/docs/reference.md index 3402411..1e60547 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -437,6 +437,25 @@ removes, settings in `installation.json` and `settings.json`) 0.51 does not see. first with `agentage daemon stop`, then install 0.51; 0.51 has no daemon and would leave this one running on its port. +## extension create + +```bash +agentage extension create [part...] [--from ] [--no-install] [--yes] +``` + +Makes `./extension-` from a template, with no git history (the author guide, `docs/extensions.md` +"Run it locally", has the parts and the steps after the clone). `--from` names the template: + +| `--from` | Takes | +| ----------------------------------------------- | ------------------------------------------------------------------------------------------ | +| not given | `agentage/platform:template`, the folder `template/` of the kit repo | +| `owner/repo` | the root of that repo's default branch (`agentage/extension-template` is the old template) | +| `owner/repo#branch` | the root of that branch | +| `owner/repo:folder`, `owner/repo#branch:folder` | only that folder (dot files included); a missing folder or a link is refused | + +The clone is shallow; only the folder is kept. A source other than the kit's `template` folder or +`agentage/extension-template` asks `run it? (y/N)` first (`--yes` does not ask). + ## extension doctor ```bash diff --git a/src/commands/extension/create-install.test.ts b/src/commands/extension/create-install.test.ts index 890f6e9..70ff5e6 100644 --- a/src/commands/extension/create-install.test.ts +++ b/src/commands/extension/create-install.test.ts @@ -136,12 +136,15 @@ describe('extension create --from another repo or a branch', () => { const NOTICE = (from: string) => `template ${from}: code from that repo will be built and run on this machine`; - test('the template itself asks nothing', async () => { - const quiet = await output(() => trustFrom('agentage/extension-template', {}, io(false).io)); - expect(quiet).toMatchObject({ error: null, stderr: '' }); - }); + test.for(['agentage/platform:template', 'agentage/extension-template'])( + 'the template itself asks nothing: %s', + async (from) => { + const quiet = await output(() => trustFrom(from, {}, io(false).io)); + expect(quiet).toMatchObject({ error: null, stderr: '' }); + } + ); - test.for(['acme/ext', 'agentage/extension-template#feature/x'])( + test.for(['acme/ext', 'agentage/extension-template#feature/x', 'agentage/platform:packages'])( '%s with no terminal needs --yes, --no-install or not', async (from) => { const refused = await output(() => trustFrom(from, {}, io(false).io)); diff --git a/src/commands/extension/create-install.ts b/src/commands/extension/create-install.ts index f99b129..5eb8d43 100644 --- a/src/commands/extension/create-install.ts +++ b/src/commands/extension/create-install.ts @@ -6,6 +6,7 @@ import { hostClient, type HostClient } from '../../lib/daemon/host-client.js'; import { CliError } from '../../lib/json-output.js'; import { loadKitTool, type LoadKitTool } from './kit-tool.js'; import { confirmed, report, summaryOf, terminalIo, type ConfirmIo } from './lifecycle.js'; +import { OWN_TEMPLATES } from './create-source.js'; import { ignoreLocal } from './up-local.js'; import { buildPackage, newerKitLine, npmIn, type Npm, type PackageBuild } from './package-build.js'; @@ -92,15 +93,13 @@ export const installCreated = async ( return { installed, url }; }; -const OWN_TEMPLATE = 'agentage/extension-template'; - // Another repo, or a branch of ours, is code nobody reviewed for you: its build script runs here. export const trustFrom = async ( from: string, opts: { yes?: boolean }, io: ConfirmIo = terminalIo() ): Promise => { - if (from === OWN_TEMPLATE) return; + if (OWN_TEMPLATES.includes(from)) return; console.error(`template ${from}: code from that repo will be built and run on this machine`); if (opts.yes) return; if (!io.isTTY) diff --git a/src/commands/extension/create-kit.test.ts b/src/commands/extension/create-kit.test.ts new file mode 100644 index 0000000..901823c --- /dev/null +++ b/src/commands/extension/create-kit.test.ts @@ -0,0 +1,123 @@ +import { + existsSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + statSync, + symlinkSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect } from 'vitest'; +import { output, test } from '../../test/config-dir.js'; +import { + CI, + EXECUTABLE, + git, + KIT_MANIFEST, + kitRepo, + pushKit, + put, + RELEASE, + TEMPLATE_FILES, +} from '../../test/kit-repo.js'; +import { runExtensionCreate, TEMPLATE } from './create.js'; + +let root = ''; +let url = ''; +const home = process.cwd(); +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'agentage-create-kit-')); + url = kitRepo(root); + process.chdir(root); +}); +afterEach(() => { + process.chdir(home); + rmSync(root, { recursive: true, force: true }); +}); + +const YES = { isTTY: true, prompt: async () => 'y' }; +const scaffoldOnly = async () => ({ installed: null, url: null }); +const asked: string[] = []; +const create = (from?: string, to = () => url) => + output(() => + runExtensionCreate( + { id: 'market', parts: [], ...(from && { from }) }, + (repo) => (asked.push(repo), to()), + scaffoldOnly, + YES + ) + ); +const made = 'extension-market'; +const read = (path: string) => readFileSync(join(root, made, path), 'utf8'); +const listed = (dir: string): string[] => + readdirSync(join(root, dir), { withFileTypes: true }).flatMap((e) => + e.isDirectory() ? listed(join(dir, e.name)).map((f) => `${e.name}/${f}`) : [e.name] + ); + +describe('extension create from the kit repo', () => { + test('the default is the folder template/ of agentage/platform', async () => { + expect(TEMPLATE).toBe('agentage/platform:template'); + const printed = await create(); + expect(printed).toMatchObject({ error: null, stderr: '' }); + expect(asked.at(-1)).toBe('agentage/platform'); + expect(printed.lines[0]).toBe( + ' template agentage/platform:template (default branch, kit 0.21.0)' + ); + }); + + test('only template/ is copied, dot files and modes kept, no kit history', async () => { + await create(); + expect(listed(made).sort()).toEqual(Object.keys(TEMPLATE_FILES).sort()); + expect(read('.repo-doctor.yml')).toBe('class: extension\n'); + expect(read('.gitignore')).toBe('node_modules/\n'); + expect(read('CLAUDE.md')).toBe('# extension-market\n'); + expect(statSync(join(root, made, EXECUTABLE)).mode & 0o111).toBe(0o111); + expect(readdirSync(root).filter((f) => f.includes('clone'))).toEqual([]); + }); + + test('repository and bugs name the new repo without the monorepo directory, private stays', async () => { + expect(KIT_MANIFEST.repository.directory).toBe('template'); + await create(); + const pkg = JSON.parse(read('package.json')) as typeof KIT_MANIFEST; + expect(pkg.repository).toEqual({ + type: 'git', + url: 'git+https://github.com/agentage/extension-market.git', + }); + expect(pkg.bugs.url).toBe('https://github.com/agentage/extension-market/issues'); + expect(pkg.homepage).toBe('https://agentage.io'); + expect(pkg.private).toBe(true); + expect(read('.github/workflows/release.yml')).toBe(RELEASE); + expect(read('.github/workflows/ci.yml')).toBe(CI); + }); + + test('--from owner/repo#branch:folder takes that folder of that branch', async () => { + git(join(root, 'kit-work'), 'checkout', '-q', '-b', 'feature/t'); + put(join(root, 'kit-work', 'other'), { ...TEMPLATE_FILES, 'branch.txt': 'b\n' }); + pushKit(root, 'feature/t'); + const printed = await create('agentage/platform#feature/t:other'); + expect(printed.lines[0]).toMatch(/^ template {2}agentage\/platform:other \(branch feature\/t,/); + expect(read('branch.txt')).toBe('b\n'); + }); + + test.for([ + ['a missing folder', 'agentage/platform:nope'], + ['a link', 'agentage/platform:link'], + ])('refuses %s with one line, no folder and no clone left', async ([, from]) => { + symlinkSync('template', join(root, 'kit-work', 'link')); + pushKit(root); + const folder = from?.split(':')[1]; + expect((await create(from)).error).toBe( + `cannot clone template ${from}: no folder ${folder} in the repo` + ); + expect(readdirSync(root).sort()).toEqual(['kit-work', 'kit.git']); + }); + + test('a clone that fails leaves no clone folder', async () => { + const printed = await create(undefined, () => `file://${root}/none`); + expect(printed.error).toMatch(/^cannot clone template agentage\/platform:template: fatal/); + expect(existsSync(join(root, made))).toBe(false); + expect(readdirSync(root).sort()).toEqual(['kit-work', 'kit.git']); + }); +}); diff --git a/src/commands/extension/create-safety.test.ts b/src/commands/extension/create-safety.test.ts new file mode 100644 index 0000000..b9479c3 --- /dev/null +++ b/src/commands/extension/create-safety.test.ts @@ -0,0 +1,92 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, vi } from 'vitest'; +import { output, test } from '../../test/config-dir.js'; +import { kitRepo, pushKit } from '../../test/kit-repo.js'; +import { runExtensionCreate } from './create.js'; +import { removeOwn } from './create-source.js'; + +let root = ''; +let url = ''; +const home = process.cwd(); +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'agentage-create-safe-')); + url = kitRepo(root); + process.chdir(root); +}); +afterEach(() => { + process.chdir(home); + vi.restoreAllMocks(); + rmSync(root, { recursive: true, force: true }); +}); + +const YES = { isTTY: true, prompt: async () => 'y' }; +const create = (from?: string) => + output(() => + runExtensionCreate( + { id: 'market', parts: [], ...(from && { from }) }, + () => url, + async () => ({ installed: null, url: null }), + YES + ) + ); +const outside = () => readdirSync(root).filter((f) => !['kit-work', 'kit.git'].includes(f)); + +describe('extension create keeps to its own folders', () => { + test('a folder of yours named like the clone folder stays as it was', async () => { + mkdirSync(join(root, '.extension-market.clone')); + writeFileSync(join(root, '.extension-market.clone', 'mine.txt'), 'mine'); + expect((await create()).error).toBeNull(); + expect(readFileSync(join(root, '.extension-market.clone', 'mine.txt'), 'utf8')).toBe('mine'); + expect(outside().sort()).toEqual(['.extension-market.clone', 'extension-market']); + }); + + test.for([ + ['in the folder', 'template/src', 'agentage/platform:template'], + ['at the root', 'src', 'agentage/extension-template'], + ])('refuses a template with a symbolic link %s, nothing left', async ([, at = '', from]) => { + mkdirSync(join(root, 'kit-work', at), { recursive: true }); + symlinkSync(root, join(root, 'kit-work', at, 'out')); + pushKit(root); + const { error } = await create(from); + expect(error).toBe(`template ${from}: a symbolic link extension-market/src/out`); + expect(outside()).toEqual([]); + expect(existsSync(join(root, 'kit-work'))).toBe(true); + }); + + test('Ctrl-C during the clone removes this run only, then the signal ends the process', async () => { + const kill = vi.spyOn(process, 'kill').mockImplementation(() => true); + const before = process.listeners('SIGINT'); + const bin = join(root, 'bin'); + mkdirSync(bin); + writeFileSync(join(bin, 'git'), '#!/bin/sh\nsleep 0.5\nexit 1\n', { mode: 0o755 }); + const path = process.env['PATH']; + process.env['PATH'] = `${bin}:${path ?? ''}`; + try { + const running = create(); + await vi.waitFor(() => expect(process.listeners('SIGINT').length).toBe(before.length + 1)); + const [onSigint] = process.listeners('SIGINT').filter((l) => !before.includes(l)); + onSigint?.('SIGINT'); + await vi.waitFor(() => expect(kill).toHaveBeenCalledWith(process.pid, 'SIGINT')); + expect(outside()).toEqual(['bin']); + await running; + } finally { + process.env['PATH'] = path; + } + expect(process.listeners('SIGINT')).toEqual(before); + }); + + test('removeOwn never throws, also for a folder already gone', () => { + expect(() => removeOwn(join(root, 'none'))).not.toThrow(); + }); +}); diff --git a/src/commands/extension/create-source.ts b/src/commands/extension/create-source.ts new file mode 100644 index 0000000..061aa56 --- /dev/null +++ b/src/commands/extension/create-source.ts @@ -0,0 +1,81 @@ +import { execFile } from 'node:child_process'; +import { lstatSync, mkdtempSync, readdirSync, renameSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { promisify } from 'node:util'; +import { holdSignals } from '../../core/loader/dispose.js'; + +const run = promisify(execFile); +// The kit repo holds the template in its folder template/; the old repo held it at its root. +export const TEMPLATE = 'agentage/platform:template'; +export const OWN_TEMPLATES = [TEMPLATE, 'agentage/extension-template']; +// owner/repo, then #branch and :folder, each optional: nothing that can pass for a flag or leave the repo. +const FROM = /^[\w.-]+\/[\w.-]+(?:#\w[\w./-]*)?(?::\w[\w.-]*(?:\/\w[\w.-]*)*)?$/; + +export const fromRefusal = (from: string): string => + !FROM.test(from) || from.includes('..') + ? `--from ${from}: owner/repo, owner/repo#branch, either with :folder` + : ''; + +// --from owner/repo[#branch][:folder], checked by fromRefusal() first; a git ref has no `:`. +export const repoRef = (from: string): { repo: string; ref?: string; folder?: string } => { + const [head = from, folder] = from.split(':'); + const [repo = head, ref] = head.split('#'); + return { repo, ...(ref && { ref }), ...(folder && { folder }) }; +}; + +// Bounded; git's own first line says why (no repo, no network, no access). +const gitClone = (url: string, from: string, into: string) => { + const { ref } = repoRef(from); + const branch = ref ? ['--branch', ref] : []; + const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' }; + return run('git', ['clone', '-q', '--depth', '1', ...branch, url, into], { + env, + timeout: 120_000, + }).catch((err: { stderr?: string; message: string }) => { + const why = (err.stderr?.trim() || err.message).split('\n')[0]; + throw new Error(`cannot clone template ${from}: ${why}`); + }); +}; + +// Real folders on the whole path: a link could point the move and the rewrite outside the repo. +const takeFolder = (into: string, folder: string, from: string, dir: string): void => { + const steps = folder.split('/').map((_, at, all) => join(into, ...all.slice(0, at + 1))); + if (!steps.every((step) => lstatSync(step, { throwIfNoEntry: false })?.isDirectory())) + throw new Error(`cannot clone template ${from}: no folder ${folder} in the repo`); + renameSync(join(into, folder), dir); +}; + +// No link at all (the kit's template has none); walked by hand, as a recursive readdir follows links in a loop. +const refuseLinks = (dir: string, from: string): void => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isSymbolicLink()) throw new Error(`template ${from}: a symbolic link ${path}`); + if (entry.isDirectory()) refuseLinks(path, from); + } +}; + +// Removes only what this run made; also the Ctrl-C path, so it never throws. +export const removeOwn = (path: string): void => rmSync(path, { recursive: true, force: true }); + +// A fresh name beside the new folder (a rename across disks fails), so no folder of yours is reused. +const cloneFolder = (dir: string, folder?: string): string => + folder ? mkdtempSync(`.${dir}.clone-`) : dir; + +// With :folder only that folder stays; a signal during the clone removes this run's folders, then exits as it would. +export const clone = async (url: string, from: string, dir: string): Promise => { + const { folder } = repoRef(from); + const into = cloneFolder(dir, folder); + const release = holdSignals(async () => [into, dir].forEach(removeOwn)); + try { + await gitClone(url, from, into); + if (folder) takeFolder(into, folder, from, dir); + removeOwn(join(dir, '.git')); + refuseLinks(dir, from); + } catch (err) { + removeOwn(dir); + throw err; + } finally { + release(); + if (folder) removeOwn(into); + } +}; diff --git a/src/commands/extension/create.test.ts b/src/commands/extension/create.test.ts index e2638d4..924c587 100644 --- a/src/commands/extension/create.test.ts +++ b/src/commands/extension/create.test.ts @@ -88,7 +88,9 @@ const scaffoldOnly = async (dir: string, install: boolean) => { return { installed: null, url: null }; }; -const create = (id: string, parts: string[] = [], from?: string) => +// The old repo with the template at its root; create-kit.test.ts has the kit's template/ folder. +const OLD = 'agentage/extension-template'; +const create = (id: string, parts: string[] = [], from = OLD) => output(() => runExtensionCreate({ id, parts, from }, () => url, scaffoldOnly, YES)); const read = (path: string) => readFileSync(join(root, 'extension-market', path), 'utf8'); const manifest = () => JSON.parse(read('package.json')) as typeof MANIFEST; @@ -96,7 +98,7 @@ const manifest = () => JSON.parse(read('package.json')) as typeof MANIFEST; describe('extension create', () => { test('--json answers with the id, folder, template and kept parts; a bad id has the code invalid_argument', async () => { const result = await runExtensionCreate( - { id: 'market', parts: ['api'], json: true, install: false }, + { id: 'market', parts: ['api'], from: OLD, json: true, install: false }, () => url, scaffoldOnly ); @@ -292,14 +294,22 @@ describe('extension create', () => { expect(existsSync(join(root, `extension-${id}`))).toBe(false); }); - test.for(['../../x', 'a/b#--upload-pack=x', 'a/b#x/../y', 'a/b#'])( - 'refuses a --from %s that is not owner/repo[#branch]', - async (from) => { - expect((await create('market', [], from)).error).toBe( - `--from ${from}: owner/repo or owner/repo#branch` - ); - } - ); + test.for([ + '../../x', + 'a/b#--upload-pack=x', + 'a/b#x/../y', + 'a/b#', + 'a/b:../x', + 'a/b:/x', + 'a/b:-x', + 'a/b:x:y', + 'a/b:x/', + 'a/b:x/..', + ])('refuses a --from %s that is not owner/repo[#branch][:folder]', async (from) => { + expect((await create('market', [], from)).error).toBe( + `--from ${from}: owner/repo, owner/repo#branch, either with :folder` + ); + }); test('--from owner/repo#branch clones that branch of the repo', async () => { const repo = url.replace('file://', ''); diff --git a/src/commands/extension/create.ts b/src/commands/extension/create.ts index 8686ba9..5497ec6 100644 --- a/src/commands/extension/create.ts +++ b/src/commands/extension/create.ts @@ -1,21 +1,17 @@ -import { execFile } from 'node:child_process'; import { existsSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { promisify } from 'node:util'; import { type Command } from 'commander'; import { addJson, CliError } from '../../lib/json-output.js'; import { installCreated, trustFrom } from './create-install.js'; +import { clone, fromRefusal, repoRef, TEMPLATE } from './create-source.js'; import { terminalIo, type ConfirmIo } from './lifecycle.js'; -const run = promisify(execFile); -export const TEMPLATE = 'agentage/extension-template'; +export { TEMPLATE }; export const PARTS = ['pages', 'ui', 'api', 'mcp', 'worker', 'store', 'cli', 'app']; const ROUTED = ['pages', 'ui', 'api', 'mcp']; // `_` is a separator here, so `template__echo` is the id too. const WORD = /(? = { cli: { keys: [['agentage', 'commands']] }, @@ -44,8 +40,7 @@ const refusal = ({ id, parts, from = TEMPLATE }: ExtensionCreateOptions, kept: s if (PARTS.includes(id)) return `id ${id} is a part name: pick another id`; if (!kept.some((part) => ROUTED.includes(part))) return `an extension needs at least one of ${ROUTED.join(', ')}`; - if (!FROM.test(from) || from.includes('..')) - return `--from ${from}: owner/repo or owner/repo#branch`; + if (fromRefusal(from)) return fromRefusal(from); return existsSync(`extension-${id}`) ? `extension-${id} exists: pick another id or remove it` : ''; @@ -71,6 +66,8 @@ const drop = (dir: string, kept: string[]): void => { if (parent) delete parent[path.at(-1) ?? '']; } } + // The new repo is the folder itself: a monorepo path of the template would point into nothing. + delete pkg['repository']?.['directory']; save(join(dir, 'package.json'), pkg); }; @@ -96,28 +93,6 @@ const renameLock = (dir: string, id: string): void => { save(join(dir, LOCK), lock); }; -// --from owner/repo[#branch], checked by refusal() first. -const repoRef = (from: string): { repo: string; ref?: string } => { - const [repo = from, ref] = from.split('#'); - return { repo, ...(ref && { ref }) }; -}; - -// Bounded, a partial folder removed; git's own first line says why (no repo, no network, no access). -const clone = async (url: string, from: string, dir: string): Promise => { - const { ref } = repoRef(from); - const branch = ref ? ['--branch', ref] : []; - const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' }; - await run('git', ['clone', '-q', '--depth', '1', ...branch, url, dir], { - env, - timeout: 120_000, - }).catch((err: { stderr?: string; message: string }) => { - rmSync(dir, { recursive: true, force: true }); - const why = (err.stderr?.trim() || err.message).split('\n')[0]; - throw new Error(`cannot clone template ${from}: ${why}`); - }); - rmSync(join(dir, '.git'), { recursive: true, force: true }); -}; - const CI = join('.github', 'workflows', 'ci.yml'); const FLOOR = /MIN_EXECUTED: '\d+'/; @@ -152,15 +127,17 @@ const printNext = (dir: string, from: string, id: string, kept: string[]): void const kit = String( json(join(dir, 'package.json'))['dependencies']?.['@agentage/extension'] ?? '?' ); - const { repo, ref } = repoRef(from); + const { repo, ref, folder } = repoRef(from); const branch = ref ? `branch ${ref}` : 'default branch'; - console.log(` template ${repo} (${branch}, kit ${kit.replace(/^[\^~]/, '')})`); + console.log( + ` template ${repo}${folder ? `:${folder}` : ''} (${branch}, kit ${kit.replace(/^[\^~]/, '')})` + ); console.log(` kept ${kept.join(', ')}`); console.log(` id ${id} · host ${id}.next.agentage.io · contract ${id}.mcpc.json`); console.log(` next cd ${dir} && agentage extension up`); }; -// Clones the template's default branch (or the #branch of --from) into ./extension- as a new working copy, no history; +// Clones the template's default branch (or the #branch of --from; only its :folder) into ./extension-, no history; // then installs its dependencies, builds it and (unless --no-install) gives it to the daemon. export const runExtensionCreate = async ( opts: ExtensionCreateOptions, @@ -188,7 +165,10 @@ export const addCreate = (group: Command, create: (o: ExtensionCreateOptions) => .description('Create ./extension- from the extension template with the parts named') .argument('', 'the extension id, also its host and contract name') .argument('[parts...]', `parts to keep (default: all eight): ${PARTS.join(', ')}`) - .option('--from ', `the template repo (default: ${TEMPLATE})`) + .option( + '--from ', + `the template repo and folder (default: ${TEMPLATE})` + ) .option('--no-install', 'build the folder, but do not give it to the daemon') .option('--yes', 'run code from another --from repo or branch without asking') ).action( diff --git a/src/test/kit-repo.ts b/src/test/kit-repo.ts new file mode 100644 index 0000000..52e761a --- /dev/null +++ b/src/test/kit-repo.ts @@ -0,0 +1,71 @@ +import { execFileSync } from 'node:child_process'; +import { chmodSync, mkdirSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +// The template's manifest as the kit holds it: create rewrites the word template in repository and bugs. +export const KIT_MANIFEST = { + name: '@agentage/extension-template', + private: true, + repository: { + type: 'git', + url: 'git+https://github.com/agentage/extension-template.git', + directory: 'template', + }, + homepage: 'https://agentage.io', + bugs: { url: 'https://github.com/agentage/extension-template/issues' }, + dependencies: { '@agentage/extension': '^0.21.0' }, + agentage: { id: 'template', parts: { api: true } }, +}; +export const RELEASE = + 'on:\n push:\n branches: [master]\n# run: npx -y @agentage/cli@0.71.0 extension release --changed\n'; +export const CI = "jobs:\n verify:\n ci-required:\n env:\n MIN_EXECUTED: '25'\n"; +export const EXECUTABLE = 'scripts/run.sh'; +export const TEMPLATE_FILES = { + 'package.json': JSON.stringify(KIT_MANIFEST, null, 2), + 'CLAUDE.md': '# extension-template\n', + '.gitignore': 'node_modules/\n', + '.repo-doctor.yml': 'class: extension\n', + '.github/workflows/ci.yml': CI, + '.github/workflows/release.yml': RELEASE, + 'src/api/index.ts': "export const create = () => 'api';\n", + [EXECUTABLE]: '#!/bin/sh\necho run\n', +}; +// The kit's own files beside template/: none of them may reach the new folder. +const KIT_FILES = { + 'package.json': '{ "name": "kit-root", "workspaces": ["packages/*"] }\n', + 'CLAUDE.md': '# the kit\n', + '.repo-doctor.yml': 'class: kit\n', + '.github/workflows/release.yml': 'name: kit release\n', + 'packages/extension/package.json': '{ "name": "@agentage/extension" }\n', +}; + +export const git = (cwd: string, ...args: string[]) => + execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', ...args], { cwd }).toString(); + +export const put = (dir: string, files: Record) => { + for (const [path, text] of Object.entries(files)) { + mkdirSync(join(dir, path, '..'), { recursive: true }); + writeFileSync(join(dir, path), text); + if (path.endsWith('.sh')) chmodSync(join(dir, path), 0o755); + } +}; + +// A bare repo shaped like the kit under root, served over file://; work is its working copy. +export const kitRepo = (root: string): string => { + const work = join(root, 'kit-work'); + put(work, KIT_FILES); + put(join(work, 'template'), TEMPLATE_FILES); + git(root, 'init', '-q', '-b', 'master', work); + git(work, 'add', '.'); + git(work, 'commit', '-q', '-m', 'kit'); + git(root, 'clone', '-q', '--bare', work, join(root, 'kit.git')); + return `file://${join(root, 'kit.git')}`; +}; + +// Commits what changed in the working copy and pushes that branch to the bare repo. +export const pushKit = (root: string, branch = 'master'): void => { + const work = join(root, 'kit-work'); + git(work, 'add', '.'); + git(work, 'commit', '-q', '-m', 'change'); + git(work, 'push', '-q', join(root, 'kit.git'), branch); +};