@automovie/template 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (20) hide show
  1. package/generated/pnpm-workspace.json +1 -0
  2. package/package.json +2 -2
  3. package/scaffold/instructions/.agents/skills/development/modules.md +6 -0
  4. package/scaffold/production/README.md +28 -0
  5. package/scaffold/production/package.json +4 -2
  6. package/scaffold/production/src/executable/motionTake/IMotionTakeSource.ts +65 -0
  7. package/scaffold/production/src/executable/motionTake/assertMotionTakeBindings.ts +64 -0
  8. package/scaffold/production/src/executable/motionTake/collectMotionTakeFiles.ts +71 -0
  9. package/scaffold/production/src/executable/motionTake/hashMotionTakeFile.ts +19 -0
  10. package/scaffold/production/src/executable/motionTake/openMotionTake.ts +178 -0
  11. package/scaffold/production/src/executable/motionTake/readMotionTakeArtifact.ts +36 -0
  12. package/scaffold/production/src/executable/motionTake/readMotionTakeInstalledLock.ts +39 -0
  13. package/scaffold/production/src/executable/motionTake/readMotionTakePackageVersion.ts +45 -0
  14. package/scaffold/production/src/executable/motionTake/readMotionTakeSource.ts +169 -0
  15. package/scaffold/production/src/executable/motionTake/replayMotionTake.ts +86 -0
  16. package/scaffold/production/src/executable/motionTake/resolveMotionTakePath.ts +41 -0
  17. package/scaffold/production/src/executable/motionTake/verifyMotionTakeEditPrefix.ts +121 -0
  18. package/scaffold/production/src/executable/motionTake/writeMotionTakeArtifact.ts +44 -0
  19. package/scaffold/production/src/executable/motionTake.ts +65 -0
  20. package/scaffold/workspace/package.json +1 -1
@@ -40,6 +40,7 @@
40
40
  "typescript": "^7.0.2"
41
41
  },
42
42
  "vite": {
43
+ "esbuild": "^0.21.5",
43
44
  "vite": "^5.4.10"
44
45
  }
45
46
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@automovie/template",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "The scaffold every AutoMovie production is created from and the function that creates its files.",
5
5
  "main": "lib/index.js",
6
6
  "exports": {
@@ -42,7 +42,7 @@
42
42
  "yaml": "^2.9.0"
43
43
  },
44
44
  "devDependencies": {
45
- "@automovie/evidence": "^0.3.1",
45
+ "@automovie/evidence": "^0.3.3",
46
46
  "@ttsc/evidence": "^0.37.1",
47
47
  "@ttsc/lint": "^0.37.1",
48
48
  "@types/node": "^22.19.17",
@@ -20,6 +20,12 @@ The object shell over a functional core is the production's own style; installed
20
20
 
21
21
  Use one definition per subject or action. Vary it through parameters or a seed. Extend the definition when it lacks a required parameter.
22
22
 
23
+ ## Places
24
+
25
+ Build reusable places with [the archetypes environment builders](https://github.com/samchon/automovie/tree/master/packages/archetypes#environments). In a set entity, place terrain, buildings, furnishing and moving facilities as named modules. Cite named frames for entrances, seats and other motion targets. Keep the production's dimensions and scene-specific selections in its set source.
26
+
27
+ Supply the prepared stage to the shot's `defineShot` builder and the prepared runtime records to `compileDefinedShot`. Actors who use overlapping floors or cross between supports cite the appropriate walkable surfaces in their staged support windows. Check the assembled scene and its contacts with the production's own capture.
28
+
23
29
  ## Shared modules
24
30
 
25
31
  Move modules shared by workspace productions to `packages/<name>` and import them from there. A standalone production keeps its modules in `src`.
@@ -52,6 +52,33 @@ With `pnpm run dev` running, `pnpm run review --url <inspector-address> --second
52
52
 
53
53
  Supply `IFilmProduction.performance` from the displayed state: `src/markFilmProduction.ts` hands it to the inspection in every host, and `marks=joint,bone,contact` draws its skeleton and contact forces. The starter's empty scene supplies none.
54
54
 
55
+ ### Save and branch a Human take
56
+
57
+ Register a take in a project-relative TypeScript module that exports `createMotionTakeSource()`. Return the [source inputs](src/executable/motionTake/IMotionTakeSource.ts), including the normal edit plan and built shots, the Human owner input for the selected shot, and any data files read outside the module graph. Register each callback used by the owner under a stable ID and version with its rebuilt function value. Keep referenced source and data files available when moving the project.
58
+
59
+ Run these commands from the production directory after choosing unused artifact paths with an existing parent directory.
60
+
61
+ ```sh
62
+ pnpm run motion:take save src/takes/rehearsal.ts rehearsal.take.json 0.55
63
+ pnpm run motion:take open src/takes/rehearsal.ts rehearsal.take.json
64
+ pnpm run motion:take branch src/takes/alternate.ts alternate.take.json
65
+ pnpm run motion:take open src/takes/alternate.ts alternate.take.json
66
+ ```
67
+
68
+ Save time is in edited-sequence seconds. The artifact carries the exact source-shot second, zero-based edit entry and seam side. Give an explicit entry after the seconds during a transition overlap. At a hard cut the default `after` selects the incoming occurrence. Use `before` after the outgoing entry number to save its exact endpoint. The Human owner uses its normal exact-time evaluation at that source instant.
69
+
70
+ Open verifies source bytes, data dependencies, provider versions, seeds and placement before returning the saved instant's poses. [The Node API](src/executable/motionTake/openMotionTake.ts) also returns a prepared performance for repeated exact source-time reads. Keep both the prepared replay and the film's editorial mapping for the duration of a preview or render. Start a fresh process after changing source modules or installed packages. Register any runtime-loaded code or data the static import graph cannot discover as project-relative dependencies.
71
+
72
+ For an alternate, register a separate take and a `branch` with the saved original's artifact and trusted source module, a count of leading outer sequence groups to retain and the new suffix composition. The save point can lie within a group. The supported join is the start of a replaceable later group. The owner preserves the active group through that join and checks the shared prefix. The original source and artifact remain available to reopen both alternatives. Edit placement and event ownership must agree through the join.
73
+
74
+ To draw an admitted take in the browser, use a trusted project subject module that admits the artifact props with `admitMotionTake` and calls [the replay adapter](src/executable/motionTake/replayMotionTake.ts) with its explicitly imported source recipe and, for a branch, the original recipe. Use the returned `performanceAt(sourceSeconds, entry)` in the draw scene's seek, with the film's normal mapping from edited to source time. Passing the entry keeps occurrences before the save's selected entry on the original take. Run `motion:take open` to verify current files, then capture or render the same verified artifact and source in a separate output directory for each alternative.
75
+
76
+ ```sh
77
+ pnpm exec automovie capture --module src/takeSubjects.ts --props rehearsal.take.json --subject rehearsal --from 0.5 --to 0.75 --out media/capture/rehearsal
78
+ ```
79
+
80
+ Version 1 reconstructs authored Human performance, including its supported prop, articulation, contact and event evaluation. It refuses opaque owner callbacks or missing inputs. Native solver snapshot restore and partial raster export resume use separate workflows.
81
+
55
82
  ## Commands
56
83
 
57
84
  | Command | Purpose |
@@ -64,6 +91,7 @@ Supply `IFilmProduction.performance` from the displayed state: `src/markFilmProd
64
91
  | `pnpm run dev` | The inspector page on `127.0.0.1:5173` |
65
92
  | `pnpm run build` | Bundle the inspector page |
66
93
  | `pnpm run physics <input-module.ts> <output.amphys> [maximum-bytes]` | Precompute an adopted physical performance outside the browser |
94
+ | `pnpm run motion:take save`, `open` or `branch` | Persist, verify or branch a registered Human take |
67
95
  | `pnpm run render --subject <film>` | Export one film as a picture-only video |
68
96
  | `pnpm run review --url <address> --seconds <s>` | Record real-time playback of the running inspector page |
69
97
  | `pnpm run capture --subject <film> [request]` | Stills, sheets and a record of a film, with views, passes, marks and round comparison |
@@ -2,7 +2,7 @@
2
2
  "name": "{{name}}",
3
3
  "private": true,
4
4
  "type": "module",
5
- "version": "0.3.1",
5
+ "version": "0.3.3",
6
6
  "license": "MIT",
7
7
  "description": "An AutoMovie coding-agent production repository.",
8
8
  "engines": {
@@ -19,7 +19,8 @@
19
19
  "capture": "automovie capture --module src/subjects.ts",
20
20
  "review": "automovie review",
21
21
  "review:setup": "playwright-core install ffmpeg chromium-headless-shell",
22
- "physics": "ttsx --cache-dir node_modules/.cache/ttsc -P tsconfig.json src/executable/physics.ts"
22
+ "physics": "ttsx --cache-dir node_modules/.cache/ttsc -P tsconfig.json src/executable/physics.ts",
23
+ "motion:take": "ttsx --cache-dir node_modules/.cache/ttsc -P tsconfig.json src/executable/motionTake.ts"
23
24
  },
24
25
  "dependencies": {
25
26
  "@automovie/archetypes": "catalog:automovie",
@@ -48,6 +49,7 @@
48
49
  "@wrtnlabs/evidence": "catalog:samchon",
49
50
  "@types/three": "catalog:three",
50
51
  "@types/react": "catalog:react",
52
+ "esbuild": "catalog:vite",
51
53
  "vite": "catalog:vite",
52
54
  "ffmpeg-static": "catalog:media"
53
55
  }
@@ -0,0 +1,65 @@
1
+ import type {
2
+ IAutoMovieComposition,
3
+ IAutoMovieEditPlan,
4
+ IAutoMovieMotionHumanPerformance,
5
+ IAutoMovieMotionTakeProvenance,
6
+ IAutoMovieShot,
7
+ } from "@automovie/interface";
8
+
9
+ /**
10
+ * Trusted production authoring inputs for one replayable Human take.
11
+ *
12
+ * @evidence contracts/development/common.md#meaningful-documentation Names the authored edit, shot inputs and provider declarations used to reopen a take.
13
+ * @evidence contracts/development/design.md#principled-representation Editorial admission consumes the normal plan and shot types. Human reconstruction consumes its owner input for the selected source shot and an optional authored suffix.
14
+ * @evidence contracts/development/design.md#minimal-and-owned-surface The installed host adds file and package provenance. The author supplies project identity, data references, explicit bindings and exact motion inputs.
15
+ * @evidence contracts/development/design.md#prohibited-design-shortcuts No serialized callbacks or poses enter the artifact; source modules rebuild runtime owner inputs and are explicitly selected by the author.
16
+ */
17
+ export interface IMotionTakeSource {
18
+ /** Stable identity common to all takes in this production. */
19
+ production: string;
20
+
21
+ /** Stable identity unique among the authored alternatives. */
22
+ take: string;
23
+
24
+ /** Editable plan admitted and resolved by the engine. */
25
+ edit: IAutoMovieEditPlan;
26
+
27
+ /** Actual authored shots referred to by the edit. */
28
+ shots: readonly IAutoMovieShot[];
29
+
30
+ /** Project-relative data dependencies not statically imported as modules. */
31
+ assets: readonly string[];
32
+
33
+ /** Explicit stable names and versions for callbacks read by the owner. */
34
+ bindings: readonly {
35
+ /** Stable provider ID. The `npm:` prefix is reserved for installed packages. */
36
+ id: string;
37
+
38
+ /** Exact version of provider behavior. */
39
+ version: string;
40
+
41
+ /** Bound function rebuilt by the trusted source module. */
42
+ value: (...args: never[]) => unknown;
43
+ }[];
44
+
45
+ /** Stable IDs and exact string seeds of other authored owners and entities. */
46
+ seeds: IAutoMovieMotionTakeProvenance["seeds"];
47
+
48
+ /** Runtime inputs for the Human source of each supported shot. */
49
+ human: Readonly<Record<string, IAutoMovieMotionHumanPerformance.IInput>>;
50
+
51
+ /** Optional separately authored suffix and trusted parent registration. */
52
+ branch?: {
53
+ /** Production-relative path of the original saved artifact. */
54
+ artifact: string;
55
+
56
+ /** Production-relative trusted module that registered the original. */
57
+ source: string;
58
+
59
+ /** Count of leading original groups whose authored behavior is retained. */
60
+ retainedParts: number;
61
+
62
+ /** Replacement composition for all groups following the retained prefix. */
63
+ suffix: IAutoMovieComposition;
64
+ };
65
+ }
@@ -0,0 +1,64 @@
1
+ import { createHumanBody } from "@automovie/motions";
2
+
3
+ import type { IMotionTakeSource } from "./IMotionTakeSource";
4
+
5
+ /**
6
+ * Reject callable data in an owner input that has no explicit named binding.
7
+ *
8
+ * @evidence contracts/development/common.md#meaningful-documentation States the owner input and named-binding requirement.
9
+ * @evidence contracts/development/implementation.md#principled-implementation Matches callable values by runtime identity against the trusted module's declarations.
10
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Builds a binding set, then checks the reachable owner data once.
11
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No function is serialized or inferred from its nonportable function name.
12
+ * @evidence contracts/development/implementation.md#efficient-algorithms The identity sets prevent duplicate walks and make each bound callable lookup constant time.
13
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work Every rebuilt input has a fresh set of callable values.
14
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Visited objects and binding identities are local to the check.
15
+ */
16
+ export function assertMotionTakeBindings(source: IMotionTakeSource): void {
17
+ const bound: Set<unknown> = new Set();
18
+ for (const binding of source.bindings) {
19
+ if (
20
+ typeof binding.value !== "function" ||
21
+ /^(?:npm|install):/u.test(binding.id)
22
+ )
23
+ throw new Error(`take-provider: invalid binding ${binding.id}`);
24
+ bound.add(binding.value);
25
+ }
26
+ const visited: Set<unknown> = new Set();
27
+ // Canonical bodies rebind their lazy internal readers through the installed owner.
28
+ for (const input of Object.values(source.human))
29
+ for (const performer of input.performers)
30
+ if (createHumanBody.owns(performer.body)) visited.add(performer.body);
31
+ /** Traverse runtime owner data without evaluating property getters. */
32
+ const visit = (value: unknown, field: string): void => {
33
+ if (typeof value === "function") {
34
+ if (!bound.has(value))
35
+ throw new Error(`take-provider: opaque provider at ${field}`);
36
+ return;
37
+ }
38
+ if (
39
+ typeof value !== "object" ||
40
+ value === null ||
41
+ visited.has(value) ||
42
+ ArrayBuffer.isView(value)
43
+ )
44
+ return;
45
+ visited.add(value);
46
+ if (value instanceof Map || value instanceof Set) {
47
+ for (const item of value) visit(item, `${field}[]`);
48
+ return;
49
+ }
50
+ for (const key of Reflect.ownKeys(value)) {
51
+ const descriptor: PropertyDescriptor = Object.getOwnPropertyDescriptor(
52
+ value,
53
+ key,
54
+ )!;
55
+ if (descriptor.get || descriptor.set)
56
+ throw new Error(
57
+ `take-provider: opaque accessor at ${field}.${String(key)}`,
58
+ );
59
+ visit(descriptor.value, `${field}.${String(key)}`);
60
+ }
61
+ };
62
+ visit(source.human, "human");
63
+ visit(source.branch?.suffix, "branch.suffix");
64
+ }
@@ -0,0 +1,71 @@
1
+ import { type BuildResult, build } from "esbuild";
2
+ import { isBuiltin } from "node:module";
3
+ import path from "node:path";
4
+
5
+ import { hashMotionTakeFile } from "./hashMotionTakeFile";
6
+ import { resolveMotionTakePath } from "./resolveMotionTakePath";
7
+
8
+ /**
9
+ * Fingerprint the runtime source graph without executing it. Installed package
10
+ * edges remain external and are returned by name for version measurement.
11
+ *
12
+ * @evidence contracts/development/common.md#meaningful-documentation Defines the source graph and the boundary with installed packages.
13
+ * @evidence contracts/development/implementation.md#principled-implementation Reads inputs and imports from the existing esbuild resolver's in-memory compilation metadata and hashes the resolved project-relative files.
14
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Discovers and confines project files, then records the independent installed package edges.
15
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No dynamic module expression that the resolver cannot account for goes unreported, and no bundle is executed or persisted.
16
+ * @evidence contracts/development/implementation.md#efficient-algorithms Builds one graph with packages external and streams the digest of each input once.
17
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work Multiple imports of the same source produce one canonical graph entry and digest.
18
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources The in-memory build output and filesystem reads are local to one call.
19
+ */
20
+ export async function collectMotionTakeFiles(
21
+ root: string,
22
+ source: string,
23
+ ): Promise<{
24
+ files: { path: string; sha256: string }[];
25
+ packages: { name: string; issuer: string }[];
26
+ }> {
27
+ const module: string = await resolveMotionTakePath(root, source, "read");
28
+ const graph: BuildResult<{ metafile: true; write: false }> = await build({
29
+ absWorkingDir: root,
30
+ entryPoints: [module],
31
+ bundle: true,
32
+ packages: "external",
33
+ platform: "node",
34
+ format: "esm",
35
+ metafile: true,
36
+ write: false,
37
+ logLevel: "silent",
38
+ logOverride: {
39
+ "unsupported-dynamic-import": "error",
40
+ "unsupported-require-call": "error",
41
+ },
42
+ });
43
+ const references: Set<string> = new Set([source, "tsconfig.json"]);
44
+ const packages: { name: string; issuer: string }[] = [];
45
+ for (const [file, input] of Object.entries(graph.metafile.inputs)) {
46
+ references.add(file.split(path.sep).join("/"));
47
+ for (const imported of input.imports) {
48
+ if (!imported.external || isBuiltin(imported.path)) continue;
49
+ const segments: string[] = imported.path.split("/");
50
+ packages.push({
51
+ name: segments
52
+ .slice(0, imported.path.startsWith("@") ? 2 : 1)
53
+ .join("/"),
54
+ issuer: file,
55
+ });
56
+ }
57
+ }
58
+
59
+ const files: { path: string; sha256: string }[] = [];
60
+ for (const reference of [...references].sort((left, right) =>
61
+ left < right ? -1 : left > right ? 1 : 0,
62
+ )) {
63
+ files.push({
64
+ path: reference,
65
+ sha256: await hashMotionTakeFile(
66
+ await resolveMotionTakePath(root, reference, "read"),
67
+ ),
68
+ });
69
+ }
70
+ return { files, packages };
71
+ }
@@ -0,0 +1,19 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+
4
+ /**
5
+ * Compute one SHA-256 over the bytes of an authored source or dependency file.
6
+ *
7
+ * @evidence contracts/development/common.md#meaningful-documentation States the digest algorithm and input bytes.
8
+ * @evidence contracts/development/implementation.md#principled-implementation Updates the digest with the chunks of a binary file stream in order.
9
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Reads one stream into one digest.
10
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No decoding, normalization or stat-based surrogate substitutes for the actual bytes.
11
+ * @evidence contracts/development/implementation.md#efficient-algorithms One linear streamed read.
12
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work Future calls must detect changed file content.
13
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Async iteration closes the stream and retains no file contents.
14
+ */
15
+ export async function hashMotionTakeFile(file: string): Promise<string> {
16
+ const hash: ReturnType<typeof createHash> = createHash("sha256");
17
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
18
+ return hash.digest("hex");
19
+ }
@@ -0,0 +1,178 @@
1
+ import {
2
+ admitMotionTake,
3
+ cutSequence,
4
+ preparePlaybackTimeline,
5
+ resolveMotionTakeAnchor,
6
+ verifyMotionTake,
7
+ } from "@automovie/engine";
8
+ import type {
9
+ IAutoMovieCut,
10
+ IAutoMovieMotionTake,
11
+ IAutoMovieMotionTakeAnchor,
12
+ } from "@automovie/interface";
13
+ import { realpath } from "node:fs/promises";
14
+
15
+ import type { IMotionTakeSource } from "./IMotionTakeSource";
16
+ import { readMotionTakeArtifact } from "./readMotionTakeArtifact";
17
+ import { readMotionTakeSource } from "./readMotionTakeSource";
18
+ import { replayMotionTake } from "./replayMotionTake";
19
+ import { resolveMotionTakePath } from "./resolveMotionTakePath";
20
+ import { verifyMotionTakeEditPrefix } from "./verifyMotionTakeEditPrefix";
21
+ import { writeMotionTakeArtifact } from "./writeMotionTakeArtifact";
22
+
23
+ /**
24
+ * Save, reopen or branch one installed production's supported Human take.
25
+ * Omit `create` to reopen and sample the same runtime at any source second.
26
+ * Only explicitly selected trusted source modules may supply owner inputs.
27
+ *
28
+ * @evidence contracts/development/common.md#meaningful-documentation Names the three operations and explains the runtime and source trust boundary.
29
+ * @evidence contracts/development/implementation.md#principled-implementation Independently admits the authoring inputs, checks current identities and cut placement, builds a Human runtime and publishes only an admitted artifact.
30
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Selects and verifies the artifact and parent, derives the current anchor and then delegates replay and publication.
31
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts Imports no executable path taken from JSON and never replaces the parent or another take.
32
+ * @evidence contracts/development/implementation.md#efficient-algorithms Prepares only the selected current cut and any branch parent, then opens only the selected Human shot.
33
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work Returns the prepared owner for any number of exact source-time reads without reopening the artifact.
34
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Owner performance lifetime transfers to the caller; no filesystem handles remain open.
35
+ */
36
+ export async function openMotionTake(props: {
37
+ root: string;
38
+ source: string;
39
+ artifact: string;
40
+ create?:
41
+ | ({ mode: "save" } & Parameters<typeof resolveMotionTakeAnchor>[2])
42
+ | { mode: "branch" };
43
+ }): Promise<{
44
+ take: IAutoMovieMotionTake;
45
+ replay: ReturnType<typeof replayMotionTake>;
46
+ }> {
47
+ const root: string = await realpath(props.root);
48
+ const saved: IAutoMovieMotionTake | undefined =
49
+ props.create === undefined
50
+ ? (await readMotionTakeArtifact(root, props.artifact)).take
51
+ : undefined;
52
+ const { recipe, provenance } = await readMotionTakeSource(
53
+ root,
54
+ props.source,
55
+ saved,
56
+ );
57
+ if (
58
+ props.create &&
59
+ (props.create.mode === "branch") !== (recipe.branch !== undefined)
60
+ )
61
+ throw new Error(
62
+ "take-provenance: select the matching original or branch source module",
63
+ );
64
+
65
+ let parent: IMotionTakeSource | undefined;
66
+ let parentCut: ReturnType<typeof resolveAnchor> | undefined;
67
+ let lineage: IAutoMovieMotionTake["parent"];
68
+ if (recipe.branch) {
69
+ const original: Awaited<ReturnType<typeof readMotionTakeArtifact>> =
70
+ await readMotionTakeArtifact(root, recipe.branch.artifact);
71
+ if (original.take.parent !== undefined)
72
+ throw new Error("take-provenance: branch the saved original take");
73
+ lineage = { path: recipe.branch.artifact, sha256: original.sha256 };
74
+ if (
75
+ saved &&
76
+ (saved.parent?.path !== lineage.path ||
77
+ saved.parent.sha256 !== lineage.sha256)
78
+ )
79
+ throw new Error(
80
+ "take-provenance: saved branch parent differs from the original artifact",
81
+ );
82
+ const originalInputs: Awaited<ReturnType<typeof readMotionTakeSource>> =
83
+ await readMotionTakeSource(root, recipe.branch.source, original.take);
84
+ parent = originalInputs.recipe;
85
+ if (
86
+ parent.branch ||
87
+ parent.production !== recipe.production ||
88
+ parent.take === recipe.take
89
+ )
90
+ throw new Error(
91
+ "take-provenance: branch requires a distinct take in the original production",
92
+ );
93
+ parentCut = resolveAnchor(parent, original.take.anchor);
94
+ verifyMotionTake(original.take, {
95
+ production: parent.production,
96
+ take: parent.take,
97
+ anchor: parentCut.anchor,
98
+ source: {
99
+ module: recipe.branch.source,
100
+ export: "createMotionTakeSource",
101
+ },
102
+ provenance: originalInputs.provenance,
103
+ });
104
+ }
105
+
106
+ const parentAnchor: IAutoMovieMotionTakeAnchor | undefined =
107
+ parentCut?.anchor;
108
+ const selection: Parameters<typeof resolveMotionTakeAnchor>[2] | undefined =
109
+ parentAnchor ??
110
+ saved?.anchor ??
111
+ (props.create?.mode === "save" ? props.create : undefined);
112
+ if (selection === undefined)
113
+ throw new Error("take-anchor: missing selected output time");
114
+ const cut: ReturnType<typeof resolveAnchor> = resolveAnchor(
115
+ recipe,
116
+ selection,
117
+ );
118
+ const { anchor } = cut;
119
+ if (
120
+ parentAnchor &&
121
+ (anchor.sequence !== parentAnchor.sequence ||
122
+ anchor.shot !== parentAnchor.shot ||
123
+ anchor.sourceSeconds !== parentAnchor.sourceSeconds)
124
+ )
125
+ throw new Error("take-anchor: branch changes the original saved placement");
126
+ const current: IAutoMovieMotionTake = admitMotionTake({
127
+ version: 1,
128
+ production: recipe.production,
129
+ take: recipe.take,
130
+ source: { module: props.source, export: "createMotionTakeSource" },
131
+ replay: "authored",
132
+ anchor,
133
+ provenance,
134
+ ...(lineage === undefined ? {} : { parent: lineage }),
135
+ });
136
+ if (saved) verifyMotionTake(saved, current);
137
+
138
+ const replay: ReturnType<typeof replayMotionTake> = replayMotionTake(
139
+ recipe,
140
+ anchor,
141
+ parent,
142
+ );
143
+ if (parentCut && replay.branchStart !== undefined)
144
+ verifyMotionTakeEditPrefix(
145
+ parentCut,
146
+ cut,
147
+ anchor.entry,
148
+ replay.branchStart,
149
+ );
150
+ if (props.create)
151
+ await writeMotionTakeArtifact(
152
+ await resolveMotionTakePath(root, props.artifact, "create"),
153
+ current,
154
+ );
155
+ return { take: current, replay };
156
+ }
157
+
158
+ /** Admit the registered edit and resolve one exact occurrence through the editorial owner. */
159
+ function resolveAnchor(
160
+ { edit, shots }: IMotionTakeSource,
161
+ selection: Parameters<typeof resolveMotionTakeAnchor>[2],
162
+ ): Parameters<typeof verifyMotionTakeEditPrefix>[0] & {
163
+ anchor: IAutoMovieMotionTakeAnchor;
164
+ } {
165
+ const cut: IAutoMovieCut = cutSequence(edit, [...shots]);
166
+ if (!cut.success)
167
+ throw new Error(
168
+ `take-anchor: edit was refused ${JSON.stringify(cut.violations)}`,
169
+ );
170
+ const prepared: ReturnType<typeof preparePlaybackTimeline> =
171
+ preparePlaybackTimeline(cut.sequence, shots);
172
+ return {
173
+ sequence: cut.sequence,
174
+ shots,
175
+ prepared,
176
+ anchor: resolveMotionTakeAnchor(cut.sequence, prepared, selection),
177
+ };
178
+ }
@@ -0,0 +1,36 @@
1
+ import { admitMotionTake } from "@automovie/engine";
2
+ import type { IAutoMovieMotionTake } from "@automovie/interface";
3
+ import { createHash } from "node:crypto";
4
+ import { readFile } from "node:fs/promises";
5
+
6
+ import { resolveMotionTakePath } from "./resolveMotionTakePath";
7
+
8
+ /**
9
+ * Read and admit the exact bytes of one production-relative artifact.
10
+ *
11
+ * @evidence contracts/development/common.md#meaningful-documentation States the file scope and admission of the read bytes.
12
+ * @evidence contracts/development/implementation.md#principled-implementation Uses the engine schema gate for untrusted JSON and computes a digest from the same file read.
13
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Resolves the file, reads it and returns the admitted data and digest.
14
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts JSON fields never determine an import or subsequent file read in this operation.
15
+ * @evidence contracts/development/implementation.md#efficient-algorithms Reads the artifact once, then parses and hashes it in linear time.
16
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work This is the first read of the selected file in the operation.
17
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Returns the admitted record and digest, without a retained byte buffer or handle.
18
+ */
19
+ export async function readMotionTakeArtifact(
20
+ root: string,
21
+ reference: string,
22
+ ): Promise<{ take: IAutoMovieMotionTake; sha256: string }> {
23
+ const bytes: Buffer = await readFile(
24
+ await resolveMotionTakePath(root, reference, "read"),
25
+ );
26
+ let raw: unknown;
27
+ try {
28
+ raw = JSON.parse(bytes.toString("utf8"));
29
+ } catch (cause) {
30
+ throw new Error(`take-schema: malformed JSON in ${reference}`, { cause });
31
+ }
32
+ return {
33
+ take: admitMotionTake(raw),
34
+ sha256: createHash("sha256").update(bytes).digest("hex"),
35
+ };
36
+ }
@@ -0,0 +1,39 @@
1
+ import { access } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ import { hashMotionTakeFile } from "./hashMotionTakeFile";
5
+
6
+ /**
7
+ * Measure the lockfile at the nearest pnpm workspace boundary, if present.
8
+ *
9
+ * @evidence contracts/development/common.md#meaningful-documentation States the workspace boundary and optional result.
10
+ * @evidence contracts/development/implementation.md#principled-implementation Locates the workspace using standard pnpm filenames and hashes its actual lockfile bytes.
11
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Walks toward the workspace root, then measures the associated lockfile once.
12
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts An artifact cannot choose the lockfile; permission and read errors are not treated as absence.
13
+ * @evidence contracts/development/implementation.md#efficient-algorithms Tests one file per directory level and only streams the matching lockfile.
14
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work Must measure installed inputs again on reopen.
15
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Leaves no open handles or retained lockfile contents.
16
+ */
17
+ export async function readMotionTakeInstalledLock(
18
+ root: string,
19
+ ): Promise<string | undefined> {
20
+ for (let directory: string = root; ; directory = path.dirname(directory)) {
21
+ const workspace: boolean = await access(
22
+ path.join(directory, "pnpm-workspace.yaml"),
23
+ ).then(
24
+ (): boolean => true,
25
+ (error: NodeJS.ErrnoException): boolean => {
26
+ if (error.code !== "ENOENT") throw error;
27
+ return false;
28
+ },
29
+ );
30
+ if (workspace)
31
+ return hashMotionTakeFile(path.join(directory, "pnpm-lock.yaml")).catch(
32
+ (error: NodeJS.ErrnoException): undefined => {
33
+ if (error.code !== "ENOENT") throw error;
34
+ return undefined;
35
+ },
36
+ );
37
+ if (directory === path.dirname(directory)) return undefined;
38
+ }
39
+ }
@@ -0,0 +1,45 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ /**
5
+ * Read the installed version of a package imported by the production source.
6
+ * Looks up the nearest manifest from the importing module's directory.
7
+ *
8
+ * @evidence contracts/development/common.md#meaningful-documentation States which version is read and where lookup begins.
9
+ * @evidence contracts/development/implementation.md#principled-implementation Searches the same ancestor node_modules directories as standard bare package resolution and reads the first manifest found.
10
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Forms the package manifest address at each ancestor, then reads its recorded version.
11
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts Global packages are outside this search, and private manifest exports do not hide the installed version.
12
+ * @evidence contracts/development/implementation.md#efficient-algorithms Checks at most one manifest per ancestor before returning.
13
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work Each invocation obtains the current installed version.
14
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Manifest reads open no persistent handles and return just a version string.
15
+ */
16
+ export async function readMotionTakePackageVersion(
17
+ root: string,
18
+ packageName: string,
19
+ issuer: string,
20
+ ): Promise<string> {
21
+ const location: string = path.dirname(path.join(root, issuer));
22
+ for (
23
+ let directory: string = location;
24
+ ;
25
+ directory = path.dirname(directory)
26
+ ) {
27
+ const data: string | null = await readFile(
28
+ path.join(directory, "node_modules", packageName, "package.json"),
29
+ "utf8",
30
+ ).catch((error: NodeJS.ErrnoException): null => {
31
+ if (error.code !== "ENOENT") throw error;
32
+ return null;
33
+ });
34
+ if (data !== null) {
35
+ const manifest: { name?: unknown; version?: unknown } = JSON.parse(data);
36
+ if (manifest.name !== packageName || typeof manifest.version !== "string")
37
+ throw new Error(
38
+ `Installed package identity is unavailable: ${packageName}`,
39
+ );
40
+ return manifest.version;
41
+ }
42
+ if (directory === path.dirname(directory)) break;
43
+ }
44
+ throw new Error(`Installed package version is unavailable: ${packageName}`);
45
+ }
@@ -0,0 +1,169 @@
1
+ import type {
2
+ IAutoMovieMotionTake,
3
+ IAutoMovieMotionTakeProvenance,
4
+ } from "@automovie/interface";
5
+ import path from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+
8
+ import type { IMotionTakeSource } from "./IMotionTakeSource";
9
+ import { assertMotionTakeBindings } from "./assertMotionTakeBindings";
10
+ import { collectMotionTakeFiles } from "./collectMotionTakeFiles";
11
+ import { hashMotionTakeFile } from "./hashMotionTakeFile";
12
+ import { readMotionTakeInstalledLock } from "./readMotionTakeInstalledLock";
13
+ import { readMotionTakePackageVersion } from "./readMotionTakePackageVersion";
14
+ import { resolveMotionTakePath } from "./resolveMotionTakePath";
15
+
16
+ /** File digests associated with source modules already loaded by this process. */
17
+ const LOADED_FILES: Map<string, string> = new Map();
18
+
19
+ /** Installed dependency identities already used under each production root. */
20
+ const LOADED_INSTALL: Map<string, string> = new Map();
21
+
22
+ /**
23
+ * Measure and rebuild the source explicitly selected by the production author.
24
+ * A saved manifest can verify input bytes before the source is evaluated.
25
+ *
26
+ * @evidence contracts/development/common.md#meaningful-documentation States who chooses the module, the pre-import guard and the provenance this host measures.
27
+ * @evidence contracts/development/implementation.md#principled-implementation Independently measures saved input files, verifies the selected module and binds the fixed trusted export and its registered function values.
28
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Separates pre-import checks, source reconstruction and provenance measurement.
29
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts No persisted field selects executable code, and the trusted source must register its callable owner inputs.
30
+ * @evidence contracts/development/implementation.md#efficient-algorithms Scans the import graph once and reuses the digests of saved files measured before the import.
31
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work Static source digests also satisfy matching explicit data dependencies.
32
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Returns source runtime inputs and scalar provenance to the operation without owning persistent handles.
33
+ */
34
+ export async function readMotionTakeSource(
35
+ root: string,
36
+ module: string,
37
+ saved?: IAutoMovieMotionTake,
38
+ ): Promise<{
39
+ recipe: IMotionTakeSource;
40
+ provenance: IAutoMovieMotionTakeProvenance;
41
+ }> {
42
+ const exportName: string = "createMotionTakeSource";
43
+ if (
44
+ saved &&
45
+ (saved.source.module !== module || saved.source.export !== exportName)
46
+ )
47
+ throw new Error(
48
+ "take-provenance: independently selected source differs from the saved source",
49
+ );
50
+
51
+ const graph: Awaited<ReturnType<typeof collectMotionTakeFiles>> =
52
+ await collectMotionTakeFiles(root, module);
53
+ const measured: Map<string, string> = new Map(
54
+ graph.files.map(({ path, sha256 }): [string, string] => [path, sha256]),
55
+ );
56
+ const expected: Map<string, string> = new Map(
57
+ saved?.provenance.files.map(({ path, sha256 }): [string, string] => [
58
+ path,
59
+ sha256,
60
+ ]),
61
+ );
62
+ for (const [reference, digest] of measured) {
63
+ if (saved && digest !== expected.get(reference))
64
+ throw new Error(
65
+ `take-provenance: files[${reference}].sha256 changed since save`,
66
+ );
67
+ const loaded: string | undefined = LOADED_FILES.get(
68
+ path.join(root, reference),
69
+ );
70
+ if (loaded !== undefined && loaded !== digest)
71
+ throw new Error(
72
+ `take-provenance: source changed in this process at ${reference}; reopen in a fresh process`,
73
+ );
74
+ }
75
+
76
+ const installed: Map<string, string> = new Map();
77
+ const resolved: Set<string> = new Set();
78
+ for (const { name, issuer } of [
79
+ { name: "@automovie/engine", issuer: "package.json" },
80
+ { name: "@automovie/motions", issuer: "package.json" },
81
+ ...graph.packages,
82
+ ]) {
83
+ const key: string = `${path.dirname(issuer)}\u0000${name}`;
84
+ if (resolved.has(key)) continue;
85
+ resolved.add(key);
86
+ const version: string = await readMotionTakePackageVersion(
87
+ root,
88
+ name,
89
+ issuer,
90
+ );
91
+ const id: string = `npm:${name}`;
92
+ const previous: string | undefined = installed.get(id);
93
+ if (previous !== undefined && previous !== version)
94
+ throw new Error(
95
+ `take-provenance: ${name} resolves to multiple versions in the source graph`,
96
+ );
97
+ installed.set(id, version);
98
+ }
99
+ const lock: string | undefined = await readMotionTakeInstalledLock(root);
100
+ if (lock !== undefined) installed.set("install:pnpm-lock", lock);
101
+ const currentInstall: Map<string, string> = new Map(installed);
102
+ if (lock === undefined) currentInstall.set("install:pnpm-lock", "");
103
+ for (const [id, version] of currentInstall) {
104
+ const loaded: string | undefined = LOADED_INSTALL.get(`${root}\u0000${id}`);
105
+ if (loaded !== undefined && loaded !== version)
106
+ throw new Error(
107
+ `take-provenance: installed dependency changed in this process at ${id}; reopen in a fresh process`,
108
+ );
109
+ }
110
+ const expectedInstalled: Map<string, string> = new Map(
111
+ saved?.provenance.providers
112
+ .filter(({ id }) => /^(?:npm|install):/u.test(id))
113
+ .map(({ id, version }): [string, string] => [id, version]),
114
+ );
115
+ if (
116
+ saved &&
117
+ (expectedInstalled.size !== installed.size ||
118
+ [...installed].some(
119
+ ([id, version]) => expectedInstalled.get(id) !== version,
120
+ ))
121
+ )
122
+ throw new Error(
123
+ "take-provenance: installed dependency versions or lockfile changed since save",
124
+ );
125
+
126
+ const sourcePath: string = await resolveMotionTakePath(root, module, "read");
127
+ for (const [reference, digest] of measured)
128
+ LOADED_FILES.set(path.join(root, reference), digest);
129
+ for (const [id, version] of currentInstall)
130
+ LOADED_INSTALL.set(`${root}\u0000${id}`, version);
131
+ const producer: {
132
+ createMotionTakeSource?: () =>
133
+ | IMotionTakeSource
134
+ | Promise<IMotionTakeSource>;
135
+ } = await import(pathToFileURL(sourcePath).href);
136
+ if (typeof producer.createMotionTakeSource !== "function")
137
+ throw new Error(`Motion take source ${module} must export ${exportName}()`);
138
+ const recipe: IMotionTakeSource = await producer.createMotionTakeSource();
139
+ assertMotionTakeBindings(recipe);
140
+
141
+ const files: IAutoMovieMotionTakeProvenance["files"][number][] = [];
142
+ for (const path of [
143
+ ...new Set([...graph.files.map((file) => file.path), ...recipe.assets]),
144
+ ].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0))) {
145
+ const sha256: string =
146
+ measured.get(path) ??
147
+ (await hashMotionTakeFile(
148
+ await resolveMotionTakePath(root, path, "read"),
149
+ ));
150
+ files.push({ path, sha256 });
151
+ }
152
+ return {
153
+ recipe,
154
+ provenance: {
155
+ files,
156
+ providers: [
157
+ ...[...installed].map(([id, version]) => ({ id, version })),
158
+ ...recipe.bindings.map(({ id, version }) => ({ id, version })),
159
+ ],
160
+ seeds: [
161
+ ...recipe.seeds,
162
+ ...Object.entries(recipe.human).map(([shot, input]) => ({
163
+ id: `human:${shot}`,
164
+ value: input.seed,
165
+ })),
166
+ ],
167
+ },
168
+ };
169
+ }
@@ -0,0 +1,86 @@
1
+ import type {
2
+ IAutoMovieMotionHumanPerformance,
3
+ IAutoMovieMotionTakeAnchor,
4
+ IAutoMovieShot,
5
+ } from "@automovie/interface";
6
+ import {
7
+ HumanPerformance,
8
+ compileHumanPerformanceContinuation,
9
+ } from "@automovie/motions";
10
+
11
+ import type { IMotionTakeSource } from "./IMotionTakeSource";
12
+
13
+ /**
14
+ * Prepare the Human owner once for reads on either side of an admitted anchor.
15
+ * A branch retains its original runtime before the owner's continuation seam.
16
+ *
17
+ * @evidence contracts/development/common.md#meaningful-documentation States the admitted anchor and the transition between prepared Human runtimes.
18
+ * @evidence contracts/development/implementation.md#principled-implementation Uses the same Human compiler for reopen and the owner's continuation gate for a changed suffix.
19
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Selects the named owner input once and returns the compiled runtime along with its source-time selector.
20
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts Rejects inconsistent shot ownership or duration instead of adjusting either clock.
21
+ * @evidence contracts/development/implementation.md#efficient-algorithms Only the selected shot is compiled; each later selector call tests one seam.
22
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work All renderer or authoring reads share the prepared original and branch runtimes.
23
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources The caller owns the returned Human performance and its preparation lifetime.
24
+ */
25
+ export function replayMotionTake(
26
+ source: IMotionTakeSource,
27
+ anchor: IAutoMovieMotionTakeAnchor,
28
+ parent?: IMotionTakeSource,
29
+ ): {
30
+ source: HumanPerformance;
31
+ branch?: HumanPerformance;
32
+ branchStart?: number;
33
+ performanceAt: (seconds: number, entry?: number) => HumanPerformance;
34
+ } {
35
+ const owner: IMotionTakeSource = parent ?? source;
36
+ const input: IAutoMovieMotionHumanPerformance.IInput | undefined =
37
+ owner.human[anchor.shot];
38
+ if (!input || !Object.hasOwn(owner.human, anchor.shot))
39
+ throw new Error(
40
+ `take-provider: no Human source registered for shot ${anchor.shot}`,
41
+ );
42
+ const authoredDuration: number | undefined = owner.shots.find(
43
+ (shot: IAutoMovieShot): boolean => shot.id === anchor.shot,
44
+ )?.duration;
45
+ if (source.branch === undefined) {
46
+ const performance: HumanPerformance = new HumanPerformance(input);
47
+ if (performance.duration !== authoredDuration)
48
+ throw new Error(
49
+ `take-anchor: Human and editorial durations differ for ${anchor.shot}`,
50
+ );
51
+ return {
52
+ source: performance,
53
+ performanceAt: (): HumanPerformance => performance,
54
+ };
55
+ }
56
+ if (!parent)
57
+ throw new Error("take-provenance: branch requires its original source");
58
+
59
+ const continuation: ReturnType<typeof compileHumanPerformanceContinuation> =
60
+ compileHumanPerformanceContinuation(
61
+ input,
62
+ anchor.sourceSeconds,
63
+ source.branch.retainedParts,
64
+ source.branch.suffix,
65
+ );
66
+ const branchDuration: number | undefined = source.shots.find(
67
+ (shot: IAutoMovieShot): boolean => shot.id === anchor.shot,
68
+ )?.duration;
69
+ if (
70
+ continuation.source.duration !== authoredDuration ||
71
+ continuation.branch.duration !== branchDuration
72
+ )
73
+ throw new Error(
74
+ `take-anchor: Human and editorial durations differ for ${anchor.shot}`,
75
+ );
76
+ return {
77
+ ...continuation,
78
+ performanceAt: (
79
+ seconds: number,
80
+ entry: number = anchor.entry,
81
+ ): HumanPerformance =>
82
+ entry < anchor.entry || seconds < continuation.branchStart
83
+ ? continuation.source
84
+ : continuation.branch,
85
+ };
86
+ }
@@ -0,0 +1,41 @@
1
+ import { isPortableMotionTakePath } from "@automovie/engine";
2
+ import { realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ /**
6
+ * Resolve a production-relative source, data or artifact path under a canonical production root.
7
+ * Creation resolves the existing parent without following an already-present destination.
8
+ *
9
+ * @evidence contracts/development/common.md#meaningful-documentation States the path scope and the distinct creation resolution.
10
+ * @evidence contracts/development/implementation.md#principled-implementation Validates the portable reference, resolves filesystem aliases and checks confinement on the resolved path.
11
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Validation, filesystem resolution and containment are successive steps.
12
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts Does not accept an absolute path, traverse a parent segment or waive the canonical root check on Windows.
13
+ * @evidence contracts/development/implementation.md#efficient-algorithms Checks each segment once and performs one filesystem resolution.
14
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work Current filesystem resolution cannot reuse a prior result after aliases change.
15
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Retains only a returned path string and opens no file handle.
16
+ */
17
+ export async function resolveMotionTakePath(
18
+ root: string,
19
+ reference: string,
20
+ mode: "read" | "create",
21
+ ): Promise<string> {
22
+ if (!isPortableMotionTakePath(reference))
23
+ throw new Error(`Expected a production-relative path: ${reference}`);
24
+
25
+ const absolute: string = path.join(root, ...reference.split("/"));
26
+ const check: string = mode === "read" ? absolute : path.dirname(absolute);
27
+ const canonical: string = await realpath(check).catch((cause: unknown) => {
28
+ throw new Error(`Motion take path is unavailable: ${reference}`, { cause });
29
+ });
30
+ const relative: string = path.relative(root, canonical);
31
+ if (
32
+ relative === ".." ||
33
+ relative.startsWith(`..${path.sep}`) ||
34
+ path.isAbsolute(relative)
35
+ )
36
+ throw new Error(`Motion take path escapes the production: ${reference}`);
37
+
38
+ return mode === "read"
39
+ ? canonical
40
+ : path.join(canonical, path.basename(absolute));
41
+ }
@@ -0,0 +1,121 @@
1
+ import { sequenceEventTimeline } from "@automovie/engine";
2
+ import type {
3
+ IAutoMoviePlaybackEntry,
4
+ IAutoMoviePlaybackEvent,
5
+ IAutoMoviePreparePlaybackTimeline,
6
+ IAutoMovieSequence,
7
+ IAutoMovieShot,
8
+ } from "@automovie/interface";
9
+ import { isDeepStrictEqual } from "node:util";
10
+
11
+ /**
12
+ * Refuse a branch that changes the original editorial view through the Human join.
13
+ *
14
+ * @evidence contracts/development/common.md#meaningful-documentation States the boundary whose placement and cues must remain fixed.
15
+ * @evidence contracts/development/implementation.md#principled-implementation Compares the admitted affine placement, visible bounds, prior shots and projected event ownership on the original output clock.
16
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure First verifies frame placement and then compares the engine's projected event ledgers.
17
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts A matching snapshot alone cannot admit an edit that changes a prior rate, trim, transition or event.
18
+ * @evidence contracts/development/implementation.md#efficient-algorithms Walks the visible prefix once and obtains ordered cues from the existing projector.
19
+ * @evidence contracts/development/implementation.md#reuse-equivalent-work Reads the prepared layouts already used to resolve the saved anchors.
20
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Borrows both editable sources and keeps neither after the check.
21
+ */
22
+ export function verifyMotionTakeEditPrefix(
23
+ original: {
24
+ sequence: IAutoMovieSequence;
25
+ prepared: IAutoMoviePreparePlaybackTimeline.IResult;
26
+ shots: readonly IAutoMovieShot[];
27
+ },
28
+ branch: {
29
+ sequence: IAutoMovieSequence;
30
+ prepared: IAutoMoviePreparePlaybackTimeline.IResult;
31
+ shots: readonly IAutoMovieShot[];
32
+ },
33
+ selected: number,
34
+ sourceJoin: number,
35
+ ): void {
36
+ const selectedEntry: IAutoMoviePlaybackEntry =
37
+ original.prepared.timeline.entries[selected]!;
38
+ const selectedShot: IAutoMovieShot = original.prepared.shotById.get(
39
+ selectedEntry.shot,
40
+ )!.shot;
41
+ const alternateShot: IAutoMovieShot = branch.prepared.shotById.get(
42
+ selectedEntry.shot,
43
+ )!.shot;
44
+ if (
45
+ selectedShot.scene !== alternateShot.scene ||
46
+ selectedShot.camera !== alternateShot.camera ||
47
+ !isDeepStrictEqual(selectedShot.cameraMotion, alternateShot.cameraMotion) ||
48
+ !isDeepStrictEqual(
49
+ selectedShot.objectMotions,
50
+ alternateShot.objectMotions,
51
+ ) ||
52
+ !isDeepStrictEqual(selectedShot.lightMotions, alternateShot.lightMotions)
53
+ )
54
+ throw new Error(
55
+ `take-anchor: branch changes shot staging or camera ${selectedEntry.shot}`,
56
+ );
57
+
58
+ let seam: number = original.prepared.timeline.runtime;
59
+ for (const entry of original.prepared.timeline.entries.slice(selected)) {
60
+ if (entry.shot !== selectedEntry.shot) continue;
61
+ const placement: IAutoMovieSequence["shots"][number] =
62
+ original.sequence.shots[entry.entry]!;
63
+ const end: number =
64
+ placement.exactSourceEnd ??
65
+ (placement.trim
66
+ ? placement.trim.start + placement.trim.duration
67
+ : selectedShot.duration);
68
+ if (sourceJoin > end) continue;
69
+ seam =
70
+ entry.start +
71
+ Math.max(0, (sourceJoin - entry.offset) / (entry.playbackRate ?? 1));
72
+ break;
73
+ }
74
+ if (original.sequence.fps !== branch.sequence.fps)
75
+ throw new Error("take-anchor: branch changes the edit frame rate");
76
+
77
+ const before: IAutoMoviePlaybackEntry[] =
78
+ original.prepared.timeline.entries.filter(
79
+ (entry): boolean => entry.start <= seam,
80
+ );
81
+ const after: IAutoMoviePlaybackEntry[] =
82
+ branch.prepared.timeline.entries.filter(
83
+ (entry): boolean => entry.start <= seam,
84
+ );
85
+ if (before.length !== after.length)
86
+ throw new Error("take-anchor: branch changes the edit prefix entries");
87
+ for (const [index, entry] of before.entries()) {
88
+ const candidate: IAutoMoviePlaybackEntry = after[index]!;
89
+ if (
90
+ entry.shot !== candidate.shot ||
91
+ entry.start !== candidate.start ||
92
+ entry.offset !== candidate.offset ||
93
+ entry.playbackRate !== candidate.playbackRate ||
94
+ Math.min(entry.start + entry.played, seam) !==
95
+ Math.min(candidate.start + candidate.played, seam) ||
96
+ !isDeepStrictEqual(
97
+ original.sequence.shots[index]?.transition,
98
+ branch.sequence.shots[index]?.transition,
99
+ )
100
+ )
101
+ throw new Error(`take-anchor: branch changes edit prefix entry ${index}`);
102
+ if (
103
+ entry.shot !== selectedEntry.shot &&
104
+ !isDeepStrictEqual(
105
+ original.prepared.shotById.get(entry.shot)?.shot,
106
+ branch.prepared.shotById.get(entry.shot)?.shot,
107
+ )
108
+ )
109
+ throw new Error(`take-anchor: branch changes prior shot ${entry.shot}`);
110
+ }
111
+
112
+ /** Project the event plays that the audience has reached at the join. */
113
+ const events = (cut: typeof original): IAutoMoviePlaybackEvent[] =>
114
+ sequenceEventTimeline(cut.sequence, [...cut.shots]).filter(
115
+ (event: IAutoMoviePlaybackEvent): boolean => event.globalTime <= seam,
116
+ );
117
+ if (!isDeepStrictEqual(events(original), events(branch)))
118
+ throw new Error(
119
+ "take-anchor: branch changes event ownership through the edit prefix",
120
+ );
121
+ }
@@ -0,0 +1,44 @@
1
+ import { link, mkdtemp, open, rmdir, unlink } from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ /**
5
+ * Publish one admitted artifact as complete JSON at an unused destination.
6
+ *
7
+ * @evidence contracts/development/common.md#meaningful-documentation States what is committed and that the destination must be unused.
8
+ * @evidence contracts/development/implementation.md#principled-implementation Stages the serialized artifact on the destination volume and links it in one exclusive operation after sync and close.
9
+ * @evidence contracts/development/implementation.md#clear-and-simple-structure Serialization, temporary write and publication have distinct steps with local cleanup.
10
+ * @evidence contracts/development/implementation.md#prohibited-implementation-shortcuts Never truncates an existing take and does not fall back to a partial direct write.
11
+ * @evidence contracts/development/implementation.md#efficient-algorithms Serializes and writes the artifact once without copying it again during publication.
12
+ * @evidenceExclude contracts/development/implementation.md#reuse-equivalent-work Each call must commit the given artifact to a distinct destination.
13
+ * @evidence contracts/development/implementation.md#bound-retention-and-release-resources Closes the write handle and cleans up the file and directory owned by this invocation.
14
+ */
15
+ export async function writeMotionTakeArtifact(
16
+ destination: string,
17
+ value: object,
18
+ ): Promise<void> {
19
+ const text: string = `${JSON.stringify(value, null, 2)}\n`;
20
+ const staging: string = await mkdtemp(
21
+ path.join(path.dirname(destination), ".motion-take-"),
22
+ );
23
+ const temporary: string = path.join(staging, "take.json");
24
+ try {
25
+ const handle: Awaited<ReturnType<typeof open>> = await open(
26
+ temporary,
27
+ "wx",
28
+ );
29
+ try {
30
+ await handle.writeFile(text, "utf8");
31
+ await handle.sync();
32
+ } finally {
33
+ await handle.close();
34
+ }
35
+
36
+ // A link publishes the whole file and refuses any existing directory entry.
37
+ await link(temporary, destination);
38
+ } finally {
39
+ await unlink(temporary).catch((error: NodeJS.ErrnoException): void => {
40
+ if (error.code !== "ENOENT") throw error;
41
+ });
42
+ await rmdir(staging);
43
+ }
44
+ }
@@ -0,0 +1,65 @@
1
+ import { openMotionTake } from "./motionTake/openMotionTake";
2
+
3
+ /** Parse the installed motion take command and print an exact reopened sample. */
4
+ async function main(): Promise<void> {
5
+ const [mode, source, artifact, seconds, entry, side, ...rest]: string[] =
6
+ process.argv.slice(2);
7
+ if (
8
+ !source ||
9
+ !artifact ||
10
+ rest.length ||
11
+ (mode === "save"
12
+ ? !seconds ||
13
+ (entry !== undefined && !/^(0|[1-9]\d*)$/u.test(entry)) ||
14
+ (side !== undefined && side !== "before" && side !== "after")
15
+ : (mode !== "open" && mode !== "branch") || seconds !== undefined)
16
+ )
17
+ throw new Error(
18
+ [
19
+ "Usage:",
20
+ "motion:take save <source-module> <new-artifact> <output-seconds> [entry] [before|after]",
21
+ "motion:take open <source-module> <artifact>",
22
+ "motion:take branch <branch-source-module> <new-artifact>",
23
+ ].join("\n"),
24
+ );
25
+
26
+ const result: Awaited<ReturnType<typeof openMotionTake>> =
27
+ await openMotionTake({
28
+ root: process.cwd(),
29
+ source,
30
+ artifact,
31
+ ...(mode === "save"
32
+ ? {
33
+ create: {
34
+ mode,
35
+ outputSeconds: Number(seconds),
36
+ ...(entry === undefined ? {} : { entry: Number(entry) }),
37
+ ...(side === "before" || side === "after" ? { side } : {}),
38
+ },
39
+ }
40
+ : mode === "branch"
41
+ ? { create: { mode } }
42
+ : {}),
43
+ });
44
+ const { anchor } = result.take;
45
+ const performance: ReturnType<typeof result.replay.performanceAt> =
46
+ result.replay.performanceAt(anchor.sourceSeconds);
47
+ if (mode === "open") {
48
+ console.log(
49
+ JSON.stringify({
50
+ take: result.take,
51
+ poses: Object.fromEntries(
52
+ performance.performers.map(({ subject }) => [
53
+ subject,
54
+ performance.pose(subject, anchor.sourceSeconds),
55
+ ]),
56
+ ),
57
+ }),
58
+ );
59
+ } else console.log(JSON.stringify(result.take));
60
+ }
61
+
62
+ void main().catch((error: unknown): void => {
63
+ console.error(error);
64
+ process.exitCode = 1;
65
+ });
@@ -2,7 +2,7 @@
2
2
  "name": "{{name}}",
3
3
  "private": true,
4
4
  "type": "module",
5
- "version": "0.3.1",
5
+ "version": "0.3.3",
6
6
  "license": "MIT",
7
7
  "description": "An AutoMovie workspace of productions and their shared packages.",
8
8
  "engines": {