@mmon-co/ncept-local 0.0.0-stage → 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +77 -2
- package/dist/days.d.ts +4 -0
- package/dist/days.js +47 -0
- package/dist/directory.d.ts +32 -0
- package/dist/directory.js +226 -0
- package/dist/exchange.d.ts +39 -0
- package/dist/exchange.js +219 -0
- package/dist/host-tools.d.ts +5 -0
- package/dist/host-tools.js +515 -0
- package/dist/host.d.ts +122 -0
- package/dist/host.js +1 -0
- package/dist/hub-auth.d.ts +46 -0
- package/dist/hub-auth.js +171 -0
- package/dist/hub.d.ts +4 -0
- package/dist/hub.js +334 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/inputs.d.ts +12 -0
- package/dist/inputs.js +266 -0
- package/dist/learning.d.ts +78 -0
- package/dist/learning.js +603 -0
- package/dist/mechanics.d.ts +3 -0
- package/dist/mechanics.js +6 -0
- package/dist/runtime.d.ts +66 -0
- package/dist/runtime.js +338 -0
- package/dist/sessions.d.ts +80 -0
- package/dist/sessions.js +125 -0
- package/dist/tar.d.ts +3 -0
- package/dist/tar.js +99 -0
- package/package.json +44 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 mmon-co
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,78 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mmon-co/ncept-local
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MIT-licensed Profile directory and learning host. Core owns Patch and log semantics; this package owns their files and the portable exchange tar.
|
|
4
|
+
|
|
5
|
+
## Directory API
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { init, openProfile, unpackDirectory } from "@mmon-co/ncept-local";
|
|
9
|
+
import { defaultTheory } from "@mmon-co/ncept-default-theory";
|
|
10
|
+
|
|
11
|
+
await init("/path/to/learn");
|
|
12
|
+
const profile = await openProfile("/path/to/learn", [defaultTheory]);
|
|
13
|
+
const reading = await profile.read();
|
|
14
|
+
const tar = await profile.pack();
|
|
15
|
+
await unpackDirectory(tar, "/path/to/moved-profile", [defaultTheory]);
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
`init` creates an empty personal Patch, empty log and reserved directories in an ordinary project directory. `profile.json` contains `format: 1`, `personal`, `theory` (Core's requirement), `theories` (package names, initially `@mmon-co/ncept-default-theory`) and `sessions` (surface → pi filename). Account credentials live at `credentialsPath()`, outside the Profile, in `~/.config/mmon/credentials.json`.
|
|
19
|
+
|
|
20
|
+
`openProfile` and `unpack` migrate a stored minor pin (or an exact web-export release) with the supplied executable Theory’s `migrations` before strict resolution. Broad requirements still use strict resolution without migration. Migration writes new immutable Patch revisions and a content-addressed log snapshot, then atomically switches `profile.json`’s personal head, Theory requirement and optional `log` digest together. Interrupted writes leave the old generation active; reopening retries pure steps from that generation. Old revision/log files remain unread history. Host futures are rebuilt from the migrated Profile; captured Session transcripts are not rewritten as futures.
|
|
21
|
+
|
|
22
|
+
`openProfile` verifies digests, the personal Patch's complete base closure, log envelopes and the configured Theory range. Its handle appends log identities, adds immutable revisions and blobs, changes the personal head, and registers trusted transcripts. Add attachment bytes before revisions referring to them. A new revision replaces its identity's prior content; its bases are other Patches, not its own history.
|
|
23
|
+
|
|
24
|
+
pi chooses `sessions/<timestamp>_<sessionId>.jsonl`. After project trust, use `registerSession(surface, filename, { trusted: true })` for an existing pi file or `writeSession` for an imported one. Files merely present in `sessions/` do not count: pi can create them before trust. Moving/opening or unpacking rewrites registered session headers' `cwd` so pi's `/resume` can find them; entry and tool-call ids stay unchanged. `parsePiSession`/`serializePiSession` preserve provider metadata and opaque non-message entries alongside the exchange's typed messages.
|
|
25
|
+
|
|
26
|
+
## Pure exchange
|
|
27
|
+
|
|
28
|
+
Import `@mmon-co/ncept-local/exchange` in Convex actions or browsers; it has no Node imports. `pack(files, theories)`, `unpack(tar, theories, { cwd })` and `validate(files, theories)` use a map of relative paths to bytes and supplied Theory identities. Package names in the manifest are data, not imports. The uncompressed ustar contains only `profile.json`, its selected log (`log.jsonl` initially, `log-<digest>.jsonl` after a write), `patches/`, `blobs/` and registered `sessions/`; the directory adapter leaves working copies in `materials/` and unrelated project files behind. Unsupported tar entry types, unsafe paths and duplicate paths are refused. `unpackDirectory` requires unused reserved directories rather than merging into an existing Profile.
|
|
29
|
+
|
|
30
|
+
## Host contract
|
|
31
|
+
|
|
32
|
+
`openHost({ profileDir, theories, model, confirm })` runs the selected Theory over the directory. The front end supplies constrained JSON replies for `judge` and `assess` (including decision grading), confirms proposals, and carries out the conversation/carry in a returned mode switch. Native catalog members are mounted by their original names; the web's envelopes remain unchanged. `web` and `bash` are the front end's capabilities, not tools implemented here. `host.hub` connects to the hosted Hub over anonymous HTTP and authenticated MCP.
|
|
33
|
+
|
|
34
|
+
Open a Session with `host.sessions.open({ mode, entry })`, then call `.turn(session, {})` for its prompt, context, Skills and bound tools. The default Theory's modes are `empty`, `charting` (entries `goal`, `mission`, `target`, `checkpoint`), `authoring` and `lesson` (entries `lesson`, `review`); the turn's `context` lists each mode's entry kinds and allowed switches. A tool is `{ name, description, schema, run(input) }`:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
const session = await host.sessions.open({ mode: "charting", entry: { kind: "goal", text: "Learn addition" } });
|
|
38
|
+
const setup = await host.sessions.turn(session, {});
|
|
39
|
+
const claim = setup.tools.find((tool) => tool.name === "record_claim")!;
|
|
40
|
+
await claim.run({ statement: "I can add one and one", stance: "knows" });
|
|
41
|
+
await host.sessions.close(session);
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
After a switch result, call `.open(result.switch)` for `next`/`aside`; for `here`, keep the same Session handle and request a fresh turn. `.close(session)` records its closing transcript through the Theory. Resume a closed Session with `.open({ mode, resume: session.id })`. Session identities, mode, scope, acceptance provenance and learner-day receipts are platform observations in `log.jsonl`, so they travel with the Profile.
|
|
45
|
+
|
|
46
|
+
The front end writes pi transcripts and registers their filenames against `session.surface` after trust. `turn(session, { learnerMessage })` takes the selected learner **message entry id**, not message text; it runs a declared reply grader before setup. Reads follow the selected pi branch, and locally recorded evidence derives its standing from its acceptance branch. A library caller without a transcript still retains tool-recorded evidence, but has no closing conversation to record.
|
|
47
|
+
|
|
48
|
+
Graph drafts stay unsaved until a confirmed `propose`. Mission and guidance/graph proposals and preference changes use `confirm`; a refusal changes no Profile files. Materials use the `local` playground, immutable blob bytes and working copies under `materials/<node>/<material>/<filename>`. Opening preserves an existing working copy. Read-back returns both the saved body and current working-copy text. Other playgrounds' Materials remain readable as saved data without claiming a runner.
|
|
49
|
+
|
|
50
|
+
`host.config.update({ ...await host.config.read(), timezone: "America/New_York" })` configures learner-days. The initial zone is the machine's IANA zone; each learner-day ends at 04:00 local, including across DST. At startup, the host raises `day.ended` once per elapsed day and records its receipt alongside the Theory's writes. No account or background daemon is needed.
|
|
51
|
+
|
|
52
|
+
## Hub and web exchange
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
// No sign-in for a public or unlisted release. Exact addresses also work: patch-id@1.0.0.
|
|
56
|
+
const ref = await host.hub.pull("https://co.mmon.co/ncept/hub/patch-example/releases/1.0.0");
|
|
57
|
+
await host.hub.signIn(); // system browser, OAuth PKCE with a loopback callback
|
|
58
|
+
const release = await host.hub.publish({ patch: ref, version: "1.0.0", title: "My map" });
|
|
59
|
+
await host.hub.exportTo("web"); // local Profile replaces web Main after confirmation
|
|
60
|
+
const imported = await host.hub.importFrom("web"); // web Profile replaces local directory after confirmation
|
|
61
|
+
// Resume a moved trusted transcript in a suitable mode:
|
|
62
|
+
await host.sessions.open({ mode: "authoring", resume: imported.sessions[0] });
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Pull verifies the closed bundle and all attachment digests before adopting its root as a direct base of the personal Patch. Publish confirms the packaged content, uploads its blobs, then captures, names and publishes a public release. Account operations require `signIn` once; the MCP SDK discovers the protected resource and authorization server, registers the client, requests `patches publish learn`, and refreshes saved tokens when necessary. Credentials are private (`0600`), outside the Profile and exchange archive.
|
|
66
|
+
|
|
67
|
+
`openHost({ ..., hub: { url, clientMetadataUrl, credentialsFile, openUrl } })` optionally overrides the Application base URL (default `https://co.mmon.co/ncept`), credential file (default `credentialsPath()`) and browser opening. For issuers using CIMD rather than dynamic registration, supply the front end's public native-client metadata document as `clientMetadataUrl` (the pi package uses pi's published identity). Front ends running remotely can present the authorization URL themselves through `openUrl`; the browser must be able to reach the host machine’s loopback callback. HTTP is allowed only for loopback development URLs.
|
|
68
|
+
|
|
69
|
+
Confirmation proposals distinguish `hub.publish`, `hub.export`, `hub.import` and `hub.choose-mission`. When the web allowance is insufficient, the host asks which Missions to keep, up to the remaining allowance, and includes the upgrade address in each proposal’s detail. Declining the final replacement leaves the live Profile unchanged. Import from web validates the archive before confirmation and stages it before replacement, retains the entire previous project directory as `<profileDir>.backup-<uuid>`, and relocates transcripts to the final directory. Reopen any active Session after replacing the Profile; unrelated old project files and Material working copies remain in the backup, not in the replacement.
|
|
70
|
+
|
|
71
|
+
## First use from this repository
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
bun test --parallel packages/local/test
|
|
75
|
+
bun run --cwd packages/local build
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The directory round-trip uses disposable temporary Profiles with a Mission, a blob, a base chain and a pi transcript; it needs neither auth nor a deployment. The corruption encounter refuses changed Patch content, a missing base and malformed log lines with their reasons.
|
package/dist/days.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { LearnerDay } from "@mmon-co/ncept-core";
|
|
2
|
+
/** Same 04:00 local boundary as the web; resolve each end independently across DST. */
|
|
3
|
+
export declare function learnerDayAt(at: string, timezone: string): LearnerDay;
|
|
4
|
+
export declare function checkedTimezone(zone: string): string;
|
package/dist/days.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Same 04:00 local boundary as the web; resolve each end independently across DST. */
|
|
2
|
+
export function learnerDayAt(at, timezone) {
|
|
3
|
+
const format = new Intl.DateTimeFormat("en-CA", {
|
|
4
|
+
timeZone: timezone,
|
|
5
|
+
year: "numeric",
|
|
6
|
+
month: "2-digit",
|
|
7
|
+
day: "2-digit",
|
|
8
|
+
hour: "2-digit",
|
|
9
|
+
minute: "2-digit",
|
|
10
|
+
second: "2-digit",
|
|
11
|
+
hourCycle: "h23",
|
|
12
|
+
});
|
|
13
|
+
const parts = (ms) => {
|
|
14
|
+
const fields = Object.fromEntries(format.formatToParts(ms).map(({ type, value }) => [type, value]));
|
|
15
|
+
return {
|
|
16
|
+
year: Number(fields.year),
|
|
17
|
+
month: Number(fields.month),
|
|
18
|
+
day: Number(fields.day),
|
|
19
|
+
hour: Number(fields.hour),
|
|
20
|
+
minute: Number(fields.minute),
|
|
21
|
+
second: Number(fields.second),
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
const local = parts(Date.parse(at));
|
|
25
|
+
const date = new Date(Date.UTC(local.year, local.month - 1, local.day - (local.hour < 4 ? 1 : 0)));
|
|
26
|
+
const boundary = (date) => {
|
|
27
|
+
const wall = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 4);
|
|
28
|
+
let instant = wall;
|
|
29
|
+
for (let i = 0; i < 4; i++) {
|
|
30
|
+
const p = parts(instant);
|
|
31
|
+
const correction = wall - Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);
|
|
32
|
+
if (correction === 0)
|
|
33
|
+
return new Date(instant).toISOString();
|
|
34
|
+
instant += correction;
|
|
35
|
+
}
|
|
36
|
+
throw new Error("Could not resolve the learner-day boundary");
|
|
37
|
+
};
|
|
38
|
+
const start = boundary(date);
|
|
39
|
+
const id = date.toISOString().slice(0, 10);
|
|
40
|
+
date.setUTCDate(date.getUTCDate() + 1);
|
|
41
|
+
return { id, start, end: boundary(date) };
|
|
42
|
+
}
|
|
43
|
+
export function checkedTimezone(zone) {
|
|
44
|
+
if (/^[+-]/.test(zone))
|
|
45
|
+
throw new Error("Expected an IANA timezone");
|
|
46
|
+
return new Intl.DateTimeFormat("en", { timeZone: zone }).resolvedOptions().timeZone;
|
|
47
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type ContentDigest, type ExactPatchRef, type PatchContent, type PatchId, type ProfileLogEntry, type TheoryRequirement } from "@mmon-co/ncept-core";
|
|
2
|
+
import { type ConfiguredTheory, type ProfileFiles, type ValidatedProfile } from "./exchange.js";
|
|
3
|
+
import { type PiSession } from "./sessions.js";
|
|
4
|
+
/** Account credentials never belong to a Profile or its exchange tar. */
|
|
5
|
+
export declare function credentialsPath(home?: string): string;
|
|
6
|
+
export interface InitOptions {
|
|
7
|
+
readonly theory?: TheoryRequirement;
|
|
8
|
+
readonly theories?: readonly string[];
|
|
9
|
+
}
|
|
10
|
+
/** Initialize inside an ordinary project directory without overwriting any Profile files. */
|
|
11
|
+
export declare function init(dir: string, options?: InitOptions): Promise<void>;
|
|
12
|
+
export interface ProfileDirectory {
|
|
13
|
+
readonly dir: string;
|
|
14
|
+
read(): Promise<ValidatedProfile>;
|
|
15
|
+
files(): Promise<ProfileFiles>;
|
|
16
|
+
appendLog(entries: readonly ProfileLogEntry[]): Promise<void>;
|
|
17
|
+
addRevision(identity: PatchId, content: PatchContent): Promise<ExactPatchRef>;
|
|
18
|
+
setPersonal(ref: ExactPatchRef): Promise<void>;
|
|
19
|
+
configure(options: InitOptions): Promise<void>;
|
|
20
|
+
addBlob(bytes: Uint8Array): Promise<ContentDigest>;
|
|
21
|
+
/** Front ends call only after accepting project trust; raw pi files are never auto-enrolled. */
|
|
22
|
+
registerSession(surface: string, filename: string, options: {
|
|
23
|
+
trusted: boolean;
|
|
24
|
+
}): Promise<void>;
|
|
25
|
+
writeSession(surface: string, session: PiSession, options: {
|
|
26
|
+
trusted: boolean;
|
|
27
|
+
}): Promise<string>;
|
|
28
|
+
pack(): Promise<Uint8Array>;
|
|
29
|
+
}
|
|
30
|
+
export declare function openProfile(dir: string, theories: readonly ConfiguredTheory[]): Promise<ProfileDirectory>;
|
|
31
|
+
/** Unpack into a new Profile, leaving unrelated project files alone and never following links. */
|
|
32
|
+
export declare function unpackDirectory(archive: Uint8Array, dir: string, theories: readonly ConfiguredTheory[]): Promise<ProfileDirectory>;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { link, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { attachmentDigest, candidateRevision, emptyPatch, isPatchId, mergeProfileLogs, PERSONAL_PATCH_ID, } from "@mmon-co/ncept-core";
|
|
6
|
+
import { DEFAULT_THEORY_PACKAGES, DEFAULT_THEORY_REQUIREMENT, jsonBytes, logBytes, liveLogPath, migrateProfileFiles, pack, parseManifest, sessionFilename, unpack, utf8, validate, } from "./exchange.js";
|
|
7
|
+
import { parsePiSession, piSessionFilename, relocatePiSession, serializePiSession, } from "./sessions.js";
|
|
8
|
+
/** Account credentials never belong to a Profile or its exchange tar. */
|
|
9
|
+
export function credentialsPath(home = homedir()) {
|
|
10
|
+
return join(home, ".config", "ncept", "credentials.json");
|
|
11
|
+
}
|
|
12
|
+
function existsError(error) {
|
|
13
|
+
return error instanceof Error && "code" in error && error.code === "EEXIST";
|
|
14
|
+
}
|
|
15
|
+
async function regular(dir, path) {
|
|
16
|
+
const parent = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : undefined;
|
|
17
|
+
if (parent && !(await lstat(join(dir, parent))).isDirectory())
|
|
18
|
+
throw new Error("Not a Profile directory: " + parent);
|
|
19
|
+
if (!(await lstat(join(dir, path))).isFile())
|
|
20
|
+
throw new Error("Not a regular Profile file: " + path);
|
|
21
|
+
return readFile(join(dir, path));
|
|
22
|
+
}
|
|
23
|
+
async function atomic(dir, path, bytes) {
|
|
24
|
+
const temp = path + "." + randomUUID() + ".tmp";
|
|
25
|
+
await writeFile(join(dir, temp), bytes, { flag: "wx" });
|
|
26
|
+
await rename(join(dir, temp), join(dir, path));
|
|
27
|
+
}
|
|
28
|
+
async function immutable(dir, path, bytes) {
|
|
29
|
+
// Stage outside patches/: an interrupted write must not leave a truncated
|
|
30
|
+
// content-addressed file that prevents reopening even the old live generation.
|
|
31
|
+
const temp = join(dir, "." + randomUUID() + ".tmp");
|
|
32
|
+
try {
|
|
33
|
+
await writeFile(temp, bytes, { flag: "wx" });
|
|
34
|
+
try {
|
|
35
|
+
await link(temp, join(dir, path));
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (!existsError(error))
|
|
39
|
+
throw error;
|
|
40
|
+
const existing = await regular(dir, path);
|
|
41
|
+
if (existing.length !== bytes.length || existing.some((byte, index) => byte !== bytes[index]))
|
|
42
|
+
throw new Error("Conflicting immutable Profile file: " + path);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
await rm(temp, { force: true });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function filesAt(dir, retries = 3) {
|
|
50
|
+
const files = new Map();
|
|
51
|
+
const manifestBytes = await regular(dir, "profile.json");
|
|
52
|
+
const manifest = parseManifest(manifestBytes);
|
|
53
|
+
files.set("profile.json", manifestBytes);
|
|
54
|
+
const logPath = liveLogPath(manifest);
|
|
55
|
+
try {
|
|
56
|
+
files.set(logPath, await regular(dir, logPath));
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
// An append may retire this snapshot after we read its manifest, even in
|
|
60
|
+
// another process. Resolve the live generation again, but bound corruption retries.
|
|
61
|
+
if (retries > 0 && error instanceof Error && "code" in error && error.code === "ENOENT")
|
|
62
|
+
return filesAt(dir, retries - 1);
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
for (const folder of ["patches", "blobs"]) {
|
|
66
|
+
if (!(await lstat(join(dir, folder))).isDirectory())
|
|
67
|
+
throw new Error("Not a Profile directory: " + folder);
|
|
68
|
+
for (const name of await readdir(join(dir, folder))) {
|
|
69
|
+
const path = folder + "/" + name;
|
|
70
|
+
files.set(path, await regular(dir, path));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
// Never scan sessions/: pi can write there before project trust is granted.
|
|
74
|
+
for (const name of Object.values(manifest.sessions)) {
|
|
75
|
+
const path = "sessions/" + name;
|
|
76
|
+
files.set(path, await regular(dir, path));
|
|
77
|
+
}
|
|
78
|
+
return files;
|
|
79
|
+
}
|
|
80
|
+
/** Initialize inside an ordinary project directory without overwriting any Profile files. */
|
|
81
|
+
export async function init(dir, options = {}) {
|
|
82
|
+
dir = resolve(dir);
|
|
83
|
+
await mkdir(dir, { recursive: true });
|
|
84
|
+
for (const folder of ["patches", "blobs", "sessions", "materials"]) {
|
|
85
|
+
await mkdir(join(dir, folder), { recursive: true });
|
|
86
|
+
if (!(await lstat(join(dir, folder))).isDirectory())
|
|
87
|
+
throw new Error("Not a Profile directory: " + folder);
|
|
88
|
+
}
|
|
89
|
+
const patch = candidateRevision(PERSONAL_PATCH_ID, emptyPatch());
|
|
90
|
+
const manifest = {
|
|
91
|
+
format: 1,
|
|
92
|
+
personal: patch.ref,
|
|
93
|
+
theory: options.theory ?? DEFAULT_THEORY_REQUIREMENT,
|
|
94
|
+
theories: options.theories ?? DEFAULT_THEORY_PACKAGES,
|
|
95
|
+
sessions: {},
|
|
96
|
+
};
|
|
97
|
+
// Reserve the manifest first: a second init must not erase a learner's log.
|
|
98
|
+
await writeFile(join(dir, "profile.json"), jsonBytes(manifest), { flag: "wx" });
|
|
99
|
+
await immutable(dir, "patches/" + patch.ref.digest + ".json", jsonBytes(emptyPatch()));
|
|
100
|
+
await writeFile(join(dir, "log.jsonl"), new Uint8Array(), { flag: "wx" });
|
|
101
|
+
}
|
|
102
|
+
export async function openProfile(dir, theories) {
|
|
103
|
+
dir = resolve(dir);
|
|
104
|
+
const stored = await filesAt(dir);
|
|
105
|
+
const initial = migrateProfileFiles(stored, theories);
|
|
106
|
+
// Immutable data first, then a single atomic live-head/log/pin switch. An interruption
|
|
107
|
+
// leaves either the old generation or the complete new one; retry never repeats a step.
|
|
108
|
+
for (const [path, bytes] of initial) {
|
|
109
|
+
if (path !== "profile.json" && !stored.has(path))
|
|
110
|
+
await immutable(dir, path, bytes);
|
|
111
|
+
}
|
|
112
|
+
const manifest = initial.get("profile.json");
|
|
113
|
+
if (manifest !== stored.get("profile.json") && manifest)
|
|
114
|
+
await atomic(dir, "profile.json", manifest);
|
|
115
|
+
const profile = validate(initial, theories);
|
|
116
|
+
// A copied or moved Profile must still appear in pi's cwd-filtered /resume list.
|
|
117
|
+
for (const filename of Object.values(profile.manifest.sessions)) {
|
|
118
|
+
const path = "sessions/" + filename;
|
|
119
|
+
const bytes = initial.get(path);
|
|
120
|
+
if (bytes) {
|
|
121
|
+
const source = new TextDecoder().decode(bytes);
|
|
122
|
+
if (parsePiSession(source).header.cwd !== dir)
|
|
123
|
+
await atomic(dir, path, utf8.encode(relocatePiSession(source, dir)));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
// Serialize this handle's mutations, including read/merge/write of the immutable-identity log.
|
|
127
|
+
let tail = Promise.resolve();
|
|
128
|
+
function serial(operation) {
|
|
129
|
+
const result = tail.then(operation);
|
|
130
|
+
tail = result.catch(() => { });
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
async function read() {
|
|
134
|
+
return validate(await filesAt(dir), theories);
|
|
135
|
+
}
|
|
136
|
+
async function manifestWith(change) {
|
|
137
|
+
const files = await filesAt(dir);
|
|
138
|
+
const manifest = { ...parseManifest(files.get("profile.json")), ...change };
|
|
139
|
+
files.set("profile.json", jsonBytes(manifest));
|
|
140
|
+
for (const filename of Object.values(manifest.sessions)) {
|
|
141
|
+
const path = "sessions/" + filename;
|
|
142
|
+
if (!files.has(path))
|
|
143
|
+
files.set(path, await regular(dir, path));
|
|
144
|
+
}
|
|
145
|
+
validate(files, theories);
|
|
146
|
+
const bytes = files.get("profile.json");
|
|
147
|
+
if (bytes)
|
|
148
|
+
await atomic(dir, "profile.json", bytes);
|
|
149
|
+
}
|
|
150
|
+
async function register(surface, filename, options) {
|
|
151
|
+
if (!options.trusted)
|
|
152
|
+
throw new Error("Project trust is required to register a Session");
|
|
153
|
+
if (!surface || !sessionFilename(filename))
|
|
154
|
+
throw new Error("Invalid Session mapping");
|
|
155
|
+
const source = new TextDecoder().decode(await regular(dir, "sessions/" + filename));
|
|
156
|
+
parsePiSession(source);
|
|
157
|
+
await atomic(dir, "sessions/" + filename, utf8.encode(relocatePiSession(source, dir)));
|
|
158
|
+
const current = (await read()).manifest;
|
|
159
|
+
await manifestWith({ sessions: { ...current.sessions, [surface]: filename } });
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
dir,
|
|
163
|
+
read,
|
|
164
|
+
files: () => filesAt(dir),
|
|
165
|
+
appendLog: (entries) => serial(async () => {
|
|
166
|
+
const current = await read();
|
|
167
|
+
const bytes = logBytes(mergeProfileLogs(current.log, entries));
|
|
168
|
+
const manifest = { ...current.manifest, log: attachmentDigest(bytes) };
|
|
169
|
+
await immutable(dir, liveLogPath(manifest), bytes);
|
|
170
|
+
await atomic(dir, "profile.json", jsonBytes(manifest));
|
|
171
|
+
// Only retire the previously live snapshot, never migration history or
|
|
172
|
+
// the unchanged snapshot produced by an empty/duplicate append.
|
|
173
|
+
const previous = liveLogPath(current.manifest);
|
|
174
|
+
if (current.manifest.log !== undefined && previous !== liveLogPath(manifest))
|
|
175
|
+
await rm(join(dir, previous), { force: true });
|
|
176
|
+
}),
|
|
177
|
+
addRevision: (identity, content) => serial(async () => {
|
|
178
|
+
if (!isPatchId(identity))
|
|
179
|
+
throw new Error("Invalid Patch identity");
|
|
180
|
+
const revision = candidateRevision(identity, content);
|
|
181
|
+
const files = await filesAt(dir);
|
|
182
|
+
const path = "patches/" + revision.ref.digest + ".json";
|
|
183
|
+
files.set(path, jsonBytes(content));
|
|
184
|
+
files.set("profile.json", jsonBytes({ ...parseManifest(files.get("profile.json")), personal: revision.ref }));
|
|
185
|
+
validate(files, theories);
|
|
186
|
+
await immutable(dir, path, jsonBytes(content));
|
|
187
|
+
return revision.ref;
|
|
188
|
+
}),
|
|
189
|
+
setPersonal: (personal) => serial(() => manifestWith({ personal })),
|
|
190
|
+
configure: (options) => serial(() => manifestWith(options)),
|
|
191
|
+
addBlob: (bytes) => serial(async () => {
|
|
192
|
+
const digest = attachmentDigest(bytes);
|
|
193
|
+
await immutable(dir, "blobs/" + digest, bytes);
|
|
194
|
+
return digest;
|
|
195
|
+
}),
|
|
196
|
+
registerSession: (surface, filename, options) => serial(() => register(surface, filename, options)),
|
|
197
|
+
writeSession: (surface, session, options) => serial(async () => {
|
|
198
|
+
if (!options.trusted)
|
|
199
|
+
throw new Error("Project trust is required to write a Session");
|
|
200
|
+
const filename = piSessionFilename(session.header);
|
|
201
|
+
const path = "sessions/" + filename;
|
|
202
|
+
await immutable(dir, path, utf8.encode(serializePiSession({ ...session, header: { ...session.header, cwd: dir } })));
|
|
203
|
+
await register(surface, filename, options);
|
|
204
|
+
return filename;
|
|
205
|
+
}),
|
|
206
|
+
pack: async () => pack(await filesAt(dir), theories),
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
/** Unpack into a new Profile, leaving unrelated project files alone and never following links. */
|
|
210
|
+
export async function unpackDirectory(archive, dir, theories) {
|
|
211
|
+
dir = resolve(dir);
|
|
212
|
+
const files = unpack(archive, theories, { cwd: dir });
|
|
213
|
+
await mkdir(dir, { recursive: true });
|
|
214
|
+
// Exclusive creation of reserved directories avoids merging with old data or symlink trees.
|
|
215
|
+
for (const folder of ["patches", "blobs", "sessions"])
|
|
216
|
+
await mkdir(join(dir, folder));
|
|
217
|
+
for (const [path, bytes] of files) {
|
|
218
|
+
if (path !== "profile.json")
|
|
219
|
+
await writeFile(join(dir, path), bytes, { flag: "wx" });
|
|
220
|
+
}
|
|
221
|
+
const manifest = files.get("profile.json");
|
|
222
|
+
if (manifest)
|
|
223
|
+
await writeFile(join(dir, "profile.json"), manifest, { flag: "wx" });
|
|
224
|
+
await mkdir(join(dir, "materials"), { recursive: true });
|
|
225
|
+
return openProfile(dir, theories);
|
|
226
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type Theory, type ContentDigest, type ExactPatchRef, type Profile, type ProfileLogEntry, type TheoryRequirement } from "@mmon-co/ncept-core";
|
|
2
|
+
import { type ProfileFiles } from "./tar.js";
|
|
3
|
+
export type { ProfileFiles } from "./tar.js";
|
|
4
|
+
export declare const DEFAULT_THEORY_PACKAGES: readonly ["@mmon-co/ncept-default-theory"];
|
|
5
|
+
export declare const DEFAULT_THEORY_REQUIREMENT: TheoryRequirement;
|
|
6
|
+
export interface ProfileManifest {
|
|
7
|
+
readonly format: 1;
|
|
8
|
+
readonly personal: ExactPatchRef;
|
|
9
|
+
/** Content-addressed live log snapshot; absent on the initial directory shape. */
|
|
10
|
+
readonly log?: ContentDigest;
|
|
11
|
+
readonly theory: TheoryRequirement;
|
|
12
|
+
/** Package names loaded by a local front end; never execute these while importing an exchange. */
|
|
13
|
+
readonly theories: readonly string[];
|
|
14
|
+
/** Only explicitly registered, trusted Sessions count; files merely present in sessions/ do not. */
|
|
15
|
+
readonly sessions: Readonly<Record<string, string>>;
|
|
16
|
+
}
|
|
17
|
+
export type ConfiguredTheory = Pick<Theory<unknown>, "id" | "version" | "migrations">;
|
|
18
|
+
export interface ValidatedProfile extends Profile {
|
|
19
|
+
readonly manifest: ProfileManifest;
|
|
20
|
+
readonly blobs: ReadonlyMap<ContentDigest, Uint8Array>;
|
|
21
|
+
/** Surface -> original pi JSONL; entry/message ids are preserved. */
|
|
22
|
+
readonly sessions: ReadonlyMap<string, string>;
|
|
23
|
+
}
|
|
24
|
+
export declare const utf8: TextEncoder;
|
|
25
|
+
export declare function jsonBytes(value: unknown): Uint8Array;
|
|
26
|
+
export declare function sessionFilename(value: unknown): value is string;
|
|
27
|
+
export declare function parseManifest(bytes: Uint8Array | undefined): ProfileManifest;
|
|
28
|
+
export declare function parseLog(bytes: Uint8Array | undefined): readonly ProfileLogEntry[];
|
|
29
|
+
export declare function logBytes(entries: readonly ProfileLogEntry[]): Uint8Array;
|
|
30
|
+
/** Pure validation; safe in a Convex action. No filesystem, package loading, or provider calls. */
|
|
31
|
+
export declare function validate(files: ProfileFiles, theories: readonly ConfiguredTheory[]): ValidatedProfile;
|
|
32
|
+
export declare function liveLogPath(manifest: ProfileManifest): string;
|
|
33
|
+
/** Migrate structurally valid live data before ordinary strict Theory resolution. */
|
|
34
|
+
export declare function migrateProfileFiles(files: ProfileFiles, theories: readonly ConfiguredTheory[]): Map<string, Uint8Array>;
|
|
35
|
+
/** Only exchange files belong in this map. The directory adapter excludes materials and untrusted sessions. */
|
|
36
|
+
export declare function pack(files: ProfileFiles, theories: readonly ConfiguredTheory[]): Uint8Array;
|
|
37
|
+
export declare function unpack(archive: Uint8Array, theories: readonly ConfiguredTheory[], options?: {
|
|
38
|
+
cwd?: string;
|
|
39
|
+
}): Map<string, Uint8Array>;
|