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/session-store.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@archwise/application': patch
'@archwise/storage': patch
'@archwise/cli': patch
---

Add the local session store. Discovered graphs are recorded as `archwise.graph` revisions in a SQLite store outside the project. The store has migrations, backups and corruption recovery. The CLI gains a protected session API, `--sessions` and `--no-store`. The Studio session UI follows separately.
9 changes: 9 additions & 0 deletions .dependency-cruiser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ export default {
from: { path: '^packages/application/src/' },
to: { pathNot: '^packages/(application|domain|schemas)/' },
},
{
name: 'storage-inward-only',
severity: 'error',
from: { path: '^packages/storage/src/' },
to: {
pathNot: '^packages/(storage|application|domain|schemas)/',
dependencyTypesNot: ['core'],
},
},
{
name: 'schemas-inward-only',
severity: 'error',
Expand Down
4 changes: 3 additions & 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. Versioned graph revision contracts (`archwise.graph` v1) exist in the core packages but are not yet wired into discovery. 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, 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.

## Development

Expand Down Expand Up @@ -37,6 +37,7 @@ The product starts from code already on a developer's machine. From a selected w
- [Architecture and local data flow](docs/architecture.md)
- [Automatic discovery and multi-repository workspaces](docs/discovery.md)
- [Real graph, sandbox, and provenance model](docs/graph-and-sandbox.md)
- [Sessions and the local store](docs/sessions.md)
- [Simulation model](docs/simulator.md)
- [AI interviewer and coach](docs/ai-coach.md)
- [Security and privacy](docs/security.md)
Expand All @@ -47,6 +48,7 @@ The product starts from code already on a developer's machine. From a selected w
- [Optional open-core business strategies](docs/business.md)
- [Architecture decision](docs/decisions/0001-local-first-open-source.md)
- [Browser workspace decision: Svelte Flow](docs/decisions/0005-svelte-flow-browser-workspace.md)
- [Local store decision: node:sqlite](docs/decisions/0006-local-store-node-sqlite.md)
- [Alpha testing guide](docs/alpha-testing.md)
- [Original README preserved as history](docs/history/README-saas-original.md)

Expand Down
2 changes: 2 additions & 0 deletions apps/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

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.

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

Source lives in `src/`. Tests ship alongside the package and run with `pnpm --filter @archwise/cli test`. Public package exports (where applicable) point only to built `dist/index.js` and its declarations.
6 changes: 6 additions & 0 deletions apps/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,11 @@
},
"bin": {
"archwise": "dist/bin.js"
},
"dependencies": {
"@archwise/application": "workspace:*",
"@archwise/domain": "workspace:*",
"@archwise/schemas": "workspace:*",
"@archwise/storage": "workspace:*"
}
}
59 changes: 47 additions & 12 deletions apps/cli/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@
import { readFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { resolve } from 'node:path';
import { basename, resolve } from 'node:path';
import { homedir } from 'node:os';
import { resolveDataDir, StoreUnavailableError } from '@archwise/storage';
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';

const metadata: unknown = JSON.parse(
readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
Expand Down Expand Up @@ -41,9 +44,31 @@ if (command.kind === 'output') {
process.stderr.write(command.result.stderr);
process.exitCode = command.result.exitCode;
} else {
const dataDir = resolveDataDir(process.env, process.platform, homedir());
try {
const result = await inspectWorkspace(command.path);
if (command.serve) {
const graph = buildArchitectureGraph(result);
const prepareRuntime = async (enabled: boolean) => {
const runtime = await prepareStore({
enabled,
dataDir,
rootPath: result.root,
rootLabel: basename(result.root),
graph,
});
for (const notice of runtime.notices) process.stderr.write(`${notice}\n`);
return runtime;
};
if (command.sessions) {
const runtime = await prepareRuntime(true);
if (runtime.kind === 'ready') {
process.stdout.write(formatSessionList(runtime.service.list()));
runtime.store.close();
} else {
process.exitCode = 1;
}
} 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;
Expand All @@ -53,16 +78,21 @@ if (command.kind === 'output') {
} catch {
process.stderr.write('Browser assets are not built; serving JSON API only.\n');
}
const server = await startLocalGraphServer(
buildArchitectureGraph(result),
assets ? { webDistPath: assets } : {},
);
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(buildArchitectureGraph(result), null, 2)}\n`);
process.stdout.write(`${JSON.stringify(graph, null, 2)}\n`);
} else if (command.json) {
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
} else {
Expand All @@ -74,13 +104,18 @@ if (command.kind === 'output') {
}
for (const warning of result.diagnostics) process.stderr.write(`Warning: ${warning}\n`);
process.stdout.write(
'Run with --graph for graph JSON. Browser Studio is not yet integrated.\n',
'Run with --graph for graph JSON, --serve to open the local Studio, or --sessions to list saved sessions.\n',
);
}
} catch (error) {
process.stderr.write(
`Unable to inspect workspace: ${error instanceof Error ? error.message : 'Unknown error'}\n`,
);
process.exitCode = 1;
if (error instanceof StoreUnavailableError) {
process.stderr.write(`${storeUnavailableMessage(error.reason, dataDir)}\n`);
process.exitCode = 2;
} else {
process.stderr.write(
`Unable to inspect workspace: ${error instanceof Error ? error.message : 'Unknown error'}\n`,
);
process.exitCode = 1;
}
}
}
8 changes: 8 additions & 0 deletions apps/cli/src/http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { ServerResponse } from 'node:http';

/** JSON response helper shared by the loopback server routes. */
export function json(res: ServerResponse, status: number, payload: unknown, head = false): void {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(head ? undefined : JSON.stringify(payload));
}
28 changes: 23 additions & 5 deletions apps/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ export type CliCommand =
readonly graph: boolean;
readonly serve: boolean;
readonly open: boolean;
/** List saved sessions for the workspace instead of inspecting. */
readonly sessions: boolean;
/** Use the local session store (disabled by --no-store). */
readonly store: boolean;
};

/** Parse arguments without touching the filesystem or executing project code. */
Expand All @@ -26,8 +30,10 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
result: {
exitCode: 0,
stdout:
'Usage: archwise [--path DIRECTORY] [--json | --graph | --serve] [--no-open] [--help | --version]\n' +
'Read-only inventory of local Node.js package manifests. --graph emits a deterministic evidence-backed graph.\n',
'Usage: archwise [--path DIRECTORY] [--json | --graph | --sessions | --serve [--no-open] [--no-store]] [--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',
stderr: '',
},
};
Expand All @@ -37,6 +43,8 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
let graph = false;
let serve = false;
let open = true;
let sessions = false;
let store = true;
for (let i = 0; i < args.length; i++) {
if (args[i] === '--path' && args[i + 1] && !args[i + 1]!.startsWith('--')) {
path = args[++i]!;
Expand All @@ -48,6 +56,10 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
serve = true;
} else if (args[i] === '--no-open') {
open = false;
} else if (args[i] === '--sessions') {
sessions = true;
} else if (args[i] === '--no-store') {
store = false;
} else {
return {
kind: 'output',
Expand All @@ -59,13 +71,13 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
};
}
}
if (Number(json) + Number(graph) + Number(serve) > 1) {
if (Number(json) + Number(graph) + Number(serve) + Number(sessions) > 1) {
return {
kind: 'output',
result: {
exitCode: 2,
stdout: '',
stderr: '--json, --graph and --serve are mutually exclusive.\n',
stderr: '--json, --graph, --sessions and --serve are mutually exclusive.\n',
},
};
}
Expand All @@ -75,7 +87,13 @@ export function parseCli(args: readonly string[], version = 'development'): CliC
result: { exitCode: 2, stdout: '', stderr: '--no-open requires --serve.\n' },
};
}
return { kind: 'inspect', path, json, graph, serve, open };
if (!serve && !store) {
return {
kind: 'output',
result: { exitCode: 2, stdout: '', stderr: '--no-store requires --serve.\n' },
};
}
return { kind: 'inspect', path, json, graph, serve, open, sessions, store };
}

/** Kept as a pure CLI helper for compatibility with the existing CLI tests. */
Expand Down
27 changes: 17 additions & 10 deletions apps/cli/src/local-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { randomBytes, timingSafeEqual } from 'node:crypto';
import { readFile, realpath, stat } from 'node:fs/promises';
import { extname, relative, resolve, sep } from 'node:path';
import type { AddressInfo } from 'node:net';
import type { SessionService } from '@archwise/application';
import type { ArchitectureGraph } from './graph.js';
import { json } from './http.js';
import { handleSessionRoute, isSessionRoute } from './session-routes.js';

const HOST = '127.0.0.1';
const MAX_PATH_LENGTH = 2048;
Expand All @@ -28,6 +31,8 @@ export interface LocalServer {
}
export interface ServerOptions {
readonly webDistPath?: string;
/** Local session store; null or absent runs without persistence. */
readonly sessions?: SessionService | null;
}

function equalSecret(value: string | undefined, secret: string): boolean {
Expand All @@ -49,12 +54,6 @@ function securityHeaders(res: ServerResponse): void {
);
}

function json(res: ServerResponse, status: number, payload: unknown, head = false): void {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(head ? undefined : JSON.stringify(payload));
}

function authorized(req: IncomingMessage, secret: string): boolean {
const auth = req.headers.authorization;
if (auth?.startsWith('Bearer ') && equalSecret(auth.slice(7), secret)) return true;
Expand Down Expand Up @@ -148,17 +147,18 @@ export async function startLocalGraphServer(
return;
}
const head = req.method === 'HEAD';
if (req.method !== 'GET' && !head) {
json(res, 405, { error: 'Method not allowed' });
return;
}
let url: URL;
try {
url = new URL(req.url, `http://${address}`);
} catch {
json(res, 400, { error: 'Invalid URL' });
return;
}
const sessionRoute = isSessionRoute(url.pathname);
if (req.method !== 'GET' && !head && !sessionRoute) {
json(res, 405, { error: 'Method not allowed' });
return;
}
if (url.pathname.startsWith('/session/')) {
const submitted = url.pathname.slice('/session/'.length);
if (
Expand Down Expand Up @@ -188,6 +188,13 @@ export async function startLocalGraphServer(
json(res, 400, { error: 'Query parameters not supported' }, head);
return;
}
if (sessionRoute) {
await handleSessionRoute(req, res, url.pathname, {
sessions: options.sessions ?? null,
origin: `http://${address}`,
});
return;
}
if (url.pathname === '/api/v1/graph') {
json(res, 200, graph, head);
return;
Expand Down
Loading
Loading