Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/studio-sessions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@archwise/web': patch
'@archwise/cli': patch
'@archwise/application': patch
---

The Studio autosaves the Sandbox to the local session store. It adds a Sessions panel (resume, rename, delete, new session), a notice when a resumed session's architecture has since changed, and `archwise --serve --resume latest|SESSION_ID`. Browser `localStorage` is no longer used for Sandbox state.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Archwise is a local-first, open-source workspace for discovering, understanding, explaining, and safely experimenting with software architecture.

> **Project status (`main`, pre-release):** local Alpha preview. Node package-manifest discovery, an evidence-backed package dependency graph, a protected loopback API, a Svelte 5/Svelte Flow Architecture Studio, a locally persisted Sandbox with versioned JSON import/export, and deterministic offline coaching questions are implemented. A deterministic **hypothetical Sandbox capacity simulation** is now available with visible assumptions; production-traffic observation, deep infrastructure discovery, multi-revision history, and AI interviewing remain future work. Discovered graphs are recorded as versioned `archwise.graph` v1 revisions, and Sandbox sessions persist in a local SQLite store outside the project (`--sessions`; the Studio switches to it in the next increment). No package or npm CLI has been published. See the [roadmap status](docs/implementation-roadmap.md#current-state) for what is delivered, what is partial, and what comes next.
> **Project status (`main`, pre-release):** local Alpha preview. Node package-manifest discovery, an evidence-backed package dependency graph, a protected loopback API, a Svelte 5/Svelte Flow Architecture Studio, an autosaved Sandbox with resumable sessions and versioned JSON import/export, and deterministic offline coaching questions are implemented. A deterministic **hypothetical Sandbox capacity simulation** is now available with visible assumptions; production-traffic observation, deep infrastructure discovery, multi-revision history, and AI interviewing remain future work. Discovered graphs are recorded as versioned `archwise.graph` v1 revisions, and Sandbox sessions autosave to a local SQLite store outside the project, so you can resume them from the Studio, `--resume` or `--sessions`. No package or npm CLI has been published. See the [roadmap status](docs/implementation-roadmap.md#current-state) for what is delivered, what is partial, and what comes next.

## Development

Expand Down
2 changes: 1 addition & 1 deletion apps/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Argument parsing, the read-only Node package-manifest inventory, evidence-backed package graph construction and the protected loopback HTTP server that serves the Studio (`--json`, `--graph`, `--serve`, `--no-open`). It never executes or imports code from the inspected project.

With `--serve`, it also records the discovered graph as an `archwise.graph` revision and serves the protected session API (see `docs/sessions.md`). `--sessions` lists saved sessions, and `--no-store` disables the local store.
With `--serve`, it also records the discovered graph as an `archwise.graph` revision and serves the protected session API (see `docs/sessions.md`). `--sessions` lists saved sessions, `--resume latest|SESSION_ID` continues one, and `--no-store` disables the local store.

Inventory, graph and server logic live here temporarily during the Alpha; ADR 0005 records the planned extraction into discovery, domain/schemas and server packages.

Expand Down
56 changes: 34 additions & 22 deletions apps/cli/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ import { inspectWorkspace } from './inventory.js';
import { buildArchitectureGraph } from './graph.js';
import { parseCli } from './index.js';
import { startLocalGraphServer } from './local-server.js';
import { formatSessionList, prepareStore, storeUnavailableMessage } from './store-runtime.js';
import {
applyResume,
formatSessionList,
prepareStore,
storeUnavailableMessage,
} from './store-runtime.js';

const metadata: unknown = JSON.parse(
readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
Expand Down Expand Up @@ -69,28 +74,35 @@ if (command.kind === 'output') {
}
} else if (command.serve) {
const runtime = await prepareRuntime(command.store);
const webDistPath = resolve(fileURLToPath(new URL('../../web/dist/', import.meta.url)));
// CLI/API mode works before the browser bundle is built; serve assets if available.
let assets: string | undefined;
try {
const { stat } = await import('node:fs/promises');
if ((await stat(resolve(webDistPath, 'index.html'))).isFile()) assets = webDistPath;
} catch {
process.stderr.write('Browser assets are not built; serving JSON API only.\n');
const resumeError = command.resume === null ? null : applyResume(runtime, command.resume);
if (resumeError !== null) {
process.stderr.write(`${resumeError}\n`);
if (runtime.kind === 'ready') runtime.store.close();
process.exitCode = 2;
} else {
const webDistPath = resolve(fileURLToPath(new URL('../../web/dist/', import.meta.url)));
// CLI/API mode works before the browser bundle is built; serve assets if available.
let assets: string | undefined;
try {
const { stat } = await import('node:fs/promises');
if ((await stat(resolve(webDistPath, 'index.html'))).isFile()) assets = webDistPath;
} catch {
process.stderr.write('Browser assets are not built; serving JSON API only.\n');
}
const server = await startLocalGraphServer(graph, {
...(assets ? { webDistPath: assets } : {}),
sessions: runtime.kind === 'ready' ? runtime.service : null,
});
process.stdout.write(`Archwise API listening at ${server.address}\n`);
process.stdout.write(`Local session URL: ${server.bootstrapUrl}\n`);
process.stdout.write(
runtime.kind === 'ready'
? 'Local session store ready (outside the project). List saved sessions with --sessions.\n'
: 'Local session store disabled for this run.\n',
);
process.stdout.write('Press Ctrl+C to stop.\n');
if (command.open && assets) openBrowser(server.bootstrapUrl);
}
const server = await startLocalGraphServer(graph, {
...(assets ? { webDistPath: assets } : {}),
sessions: runtime.kind === 'ready' ? runtime.service : null,
});
process.stdout.write(`Archwise API listening at ${server.address}\n`);
process.stdout.write(`Local session URL: ${server.bootstrapUrl}\n`);
process.stdout.write(
runtime.kind === 'ready'
? 'Local session store ready (outside the project). List saved sessions with --sessions.\n'
: 'Local session store disabled for this run.\n',
);
process.stdout.write('Press Ctrl+C to stop.\n');
if (command.open && assets) openBrowser(server.bootstrapUrl);
} else if (command.graph) {
process.stdout.write(`${JSON.stringify(graph, null, 2)}\n`);
} else if (command.json) {
Expand Down
35 changes: 32 additions & 3 deletions apps/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export type CliCommand =
readonly sessions: boolean;
/** Use the local session store (disabled by --no-store). */
readonly store: boolean;
/** `latest` or a session ID to resume when serving; null starts a fresh session. */
readonly resume: string | null;
};

/** Parse arguments without touching the filesystem or executing project code. */
Expand All @@ -30,10 +32,11 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
result: {
exitCode: 0,
stdout:
'Usage: archwise [--path DIRECTORY] [--json | --graph | --sessions | --serve [--no-open] [--no-store]] [--help | --version]\n' +
'Usage: archwise [--path DIRECTORY] [--json | --graph | --sessions | --serve [--no-open] [--no-store | --resume latest|SESSION_ID]] [--help | --version]\n' +
'Read-only inventory of local Node.js package manifests. --graph emits a deterministic evidence-backed graph.\n' +
'--sessions lists saved Sandbox sessions for this project. --serve opens the local Studio and records\n' +
'the discovered graph in the local store outside the project; --no-store disables the store.\n',
'the discovered graph in the local store outside the project; --no-store disables the store.\n' +
'--resume continues the newest (latest) or a specific saved session instead of a fresh one.\n',
stderr: '',
},
};
Expand All @@ -45,6 +48,7 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
let open = true;
let sessions = false;
let store = true;
let resume: string | null = null;
for (let i = 0; i < args.length; i++) {
if (args[i] === '--path' && args[i + 1] && !args[i + 1]!.startsWith('--')) {
path = args[++i]!;
Expand All @@ -60,6 +64,20 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
sessions = true;
} else if (args[i] === '--no-store') {
store = false;
} else if (args[i] === '--resume') {
const value = args[i + 1];
if (!value || !(value === 'latest' || /^ses-[0-9a-f]{24}$/.test(value))) {
return {
kind: 'output',
result: {
exitCode: 2,
stdout: '',
stderr: '--resume expects "latest" or a session ID from --sessions.\n',
},
};
}
resume = value;
i += 1;
} else {
return {
kind: 'output',
Expand Down Expand Up @@ -93,7 +111,18 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
result: { exitCode: 2, stdout: '', stderr: '--no-store requires --serve.\n' },
};
}
return { kind: 'inspect', path, json, graph, serve, open, sessions, store };
if (resume !== null && (!serve || !store)) {
return {
kind: 'output',
result: {
exitCode: 2,
stdout: '',
stderr:
'--resume requires --serve and the local store (it cannot be combined with --no-store).\n',
},
};
}
return { kind: 'inspect', path, json, graph, serve, open, sessions, store, resume };
}

/** Kept as a pure CLI helper for compatibility with the existing CLI tests. */
Expand Down
8 changes: 8 additions & 0 deletions apps/cli/src/session-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,14 @@ export async function handleSessionRoute(
notFound(res);
return;
}
if (pathname === `${PREFIX}/new` && method === 'POST') {
if (req.headers.origin !== context.origin) {
json(res, 403, { error: 'Same-origin request required' });
return;
}
json(res, 200, { ...sessions.startNew(), storeEnabled: true });
return;
}
if (pathname === PREFIX && method === 'GET') {
json(res, 200, { sessions: sessions.list() });
return;
Expand Down
20 changes: 20 additions & 0 deletions apps/cli/src/store-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,26 @@ export async function prepareStore(options: PrepareStoreOptions): Promise<StoreR
}
}

/** Resolves `latest` or a session ID to a stored session of this workspace, or null. */
export function resumeTarget(service: SessionService, value: string): string | null {
if (value === 'latest') return service.list()[0]?.id ?? null;
return service.get(value).ok ? value : null;
}

/**
* Makes the requested session current before serving. Returns an actionable error message
* when it cannot, in which case the caller exits with code 2 without starting a server.
*/
export function applyResume(runtime: StoreRuntime, value: string): string | null {
if (runtime.kind !== 'ready') {
return 'The local store is unavailable in this run, so no session can be resumed.';
}
const target = resumeTarget(runtime.service, value);
if (target === null) return `No saved session matches "${value}". Run --sessions to list them.`;
runtime.service.resume(target);
return null;
}

export function storeUnavailableMessage(reason: StoreUnavailableReason, dataDir: string): string {
switch (reason) {
case 'newer-schema':
Expand Down
18 changes: 18 additions & 0 deletions apps/cli/tests/cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ test('defaults to read-only inspection of current directory', () => {
open: true,
sessions: false,
store: true,
resume: null,
});
});

Expand All @@ -24,6 +25,7 @@ test('accepts a workspace path and graph output', () => {
open: true,
sessions: false,
store: true,
resume: null,
});
});

Expand All @@ -47,6 +49,7 @@ test('prints help and rejects unsupported or contradictory options', () => {
open: false,
sessions: false,
store: true,
resume: null,
});
});

Expand All @@ -66,3 +69,18 @@ test('help does not claim the Studio already saves sessions', () => {
expect(help).not.toMatch(/saves Sandbox sessions/);
expect(help).toContain('local store');
});

test('--resume requires --serve, the store, and latest or a session id', () => {
expect(parseCli(['--serve', '--resume', 'latest'])).toMatchObject({
serve: true,
resume: 'latest',
});
const id = `ses-${'a'.repeat(24)}`;
expect(parseCli(['--serve', '--resume', id])).toMatchObject({ resume: id });
expect(parseCli(['--serve'])).toMatchObject({ resume: null });
expect(runCli(['--resume', 'latest']).exitCode).toBe(2);
expect(runCli(['--serve', '--resume', 'ses-bad']).exitCode).toBe(2);
expect(runCli(['--serve', '--resume']).exitCode).toBe(2);
expect(runCli(['--serve', '--resume', 'latest', '--no-store']).exitCode).toBe(2);
expect(runCli(['--help']).stdout).toContain('--resume');
});
12 changes: 12 additions & 0 deletions apps/cli/tests/session-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,3 +200,15 @@ test('non-session routes still reject mutating methods', async () => {
const { call } = await start();
expect((await call('/api/v1/graph', { method: 'POST' })).status).toBe(405);
});

test('POST /new reserves a fresh current session for same-origin callers', async () => {
const { call } = await start();
const before = (await (await call('/api/v1/sessions/current')).json()) as { id: string };
const denied = await call('/api/v1/sessions/new', { method: 'POST', headers: { origin: '' } });
expect(denied.status).toBe(403);
const created = await call('/api/v1/sessions/new', { method: 'POST' });
expect(created.status).toBe(200);
const body = (await created.json()) as { id: string; persisted: boolean; storeEnabled: boolean };
expect(body).toMatchObject({ persisted: false, storeEnabled: true });
expect(body.id).not.toBe(before.id);
});
27 changes: 27 additions & 0 deletions apps/cli/tests/store-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,30 @@ test('a data directory outside the root opens the store', async () => {
expect(runtime.kind).toBe('ready');
if (runtime.kind === 'ready') runtime.store.close();
});

test('resumeTarget resolves latest and known ids only', async () => {
const { resumeTarget } = await import('../src/store-runtime.js');
const root = temp('archwise-root-');
const data = temp('archwise-data-');
const runtime = await prepareStore({
enabled: true,
dataDir: data,
rootPath: root,
rootLabel: 'r',
graph,
});
if (runtime.kind !== 'ready') throw new Error('store expected');
try {
expect(resumeTarget(runtime.service, 'latest')).toBeNull();
const id = runtime.service.current().id;
runtime.service.saveSandbox(
id,
JSON.stringify({ format: 'archwise-sandbox', version: 1, nodes: [], draft: {} }),
);
expect(resumeTarget(runtime.service, 'latest')).toBe(id);
expect(resumeTarget(runtime.service, id)).toBe(id);
expect(resumeTarget(runtime.service, `ses-${'f'.repeat(24)}`)).toBeNull();
} finally {
runtime.store.close();
}
});
2 changes: 1 addition & 1 deletion apps/web/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# web

Svelte 5 and Svelte Flow Architecture Studio (ADR 0005). It covers Explore mode for the discovered package graph and its evidence, plus the Sandbox: component catalog, custom nodes, inspector, semantic connections, the deterministic hypothetical simulation, A/B comparison, local persistence with JSON import/export, and the offline coach. It has no filesystem access and receives the graph only from the authenticated local API.
Svelte 5 and Svelte Flow Architecture Studio (ADR 0005). It covers Explore mode for the discovered package graph and its evidence, plus the Sandbox: component catalog, custom nodes, inspector, semantic connections, the deterministic hypothetical simulation, A/B comparison, session autosave and resume through the local session API (`session-client.ts`, `autosave.ts`, `SessionsPanel.svelte`), JSON import/export, and the offline coach. It has no filesystem access and receives the graph only from the authenticated local API.

The simulator, persistence and coach live here temporarily during the Alpha; ADR 0005 records their planned extraction into packages.

Expand Down
Loading
Loading