Open-source, local-first social media research agent for Instagram, TikTok, and LinkedIn. Jev routes read-only steps; socai CLI captures cited browser evidence.
JavaScript agent-skillsai-agentsbrowser-agentbrowser-automationdecision-modeldeep-researchinstagramjevlinkedinlocal-firstopen-sourceosintresearch-agentsocaisocial-listeningsocial-mediasocial-media-researchsocmintsystem-onetiktok
Add versioned import-only Reel library contract (#127)
zeeuus82f02e6f4c609
diff --git a/README.md b/README.mdindex c34f943..b42921f 100644--- a/README.md+++ b/README.md@@ -100,6 +100,14 @@ The report model defaults to `openai/gpt-4o-mini` and may incur normal providerThe complete field limits, file permissions, provider-retention boundary, browser-session boundary, and recovery procedure are documented in [Security and data flow](SECURITY.md#data-flow-credentials-and-retention).+## Local Reel imports++The import-only API accepts versioned, already processed Reel collections and+stores their normalized transcripts, classifications and nullable metrics in the+isolated local state directory. See the [version 1 contract](docs/reels-import.md)+for the schema, identity rules, endpoints and offline validation. A library UI+and automated collection are outside this first slice.+## Recorded evidence| Recorded run | Captured result | Elapsed time | Verification boundary |diff --git a/docs/creator-lab-license.txt b/docs/creator-lab-license.txtnew file mode 100644index 0000000..4941cad--- /dev/null+++ b/docs/creator-lab-license.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Artem Novitckii++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/docs/reels-import.md b/docs/reels-import.mdnew file mode 100644index 0000000..e14eea8--- /dev/null+++ b/docs/reels-import.md@@ -0,0 +1,95 @@+# Reel imports: version 1++This first slice of #124 imports already processed JSON. It adds no UI, browser+operations, provider calls or media downloads. Future producers (#125) should+target this contract instead of persisting their raw provider responses.++## Input++Send a JSON object to `POST /api/reels` with `Content-Type: application/json` and+an `Origin` matching the loopback server. Maximum input and normalized size:+10,000,000 UTF-8 bytes, with 1–1,000 items. `GET /api/reels` lists collections;+`GET /api/reels/<library-id>` reopens one. Invalid imports leave prior data intact.++The required envelope is `{ schemaVersion: 1, id, creator, posts }`. `id` is a+stable source collection ID; each post requires its own stable `id` and an+Instagram `url`. IDs are case-sensitive, 1–128 ASCII letters, digits, dots,+underscores, colons or hyphens, starting with a letter or digit. Creator handles+are normalized to lowercase. Collection `createdAt` and source `status` are+optional. Unsupported or missing schema versions fail closed.++A Creator Lab adapter can add `schemaVersion: 1` to its export after checking+these fields and mapping producer-specific states. Do not use filenames as IDs+or fill missing plays from views. Unversioned exports require this explicit+adapter step; the importer does not guess future producer formats.++Each post accepts:++- `creator`, `caption`, RFC 3339 `publishedAt`, `capturedAt` (or `scrapedAt`)+ with an explicit timezone, `duration`, `plays`, `views`, `likes`, and `comments`.+- `transcript: { text, segments: [{ text, start, end }] }`. Times are seconds;+ every segment requires string text, missing times stay `null`, and known start+ times must be in nondecreasing order. Negative, nonnumeric or reversed times+ are rejected.+- `analysis: { labels, anatomy }`. Labels use the eight dimensions and enums+ in `src/reels-contract.js`; every label has a confidence in `[0, 1]`. Anatomy+ segments add `value` (script role) and nullable `confidence` to a timed segment.+ Classification requires a nonempty transcript. Each segment array is limited+ to 200 entries; transcript and segment text to 48,000 characters, captions to+ 12,000. Oversized or malformed text is rejected.+- `status`: absent, `pending`, `ready`, `unclassified`, `classified`,+ `no_audio`, `no_speech`, `excluded`, `failed`, or `error`.+ `excludedReason` also marks exclusion. Error and excluded rows cannot carry a+ classification. Raw errors and exclusion text are replaced with fixed notes.++All fixtures in `test/fixtures/reels-import-v1.json` are synthetic; their URLs+are validation examples, not fetched or asserted to be real posts.++## Normalized contract++`schemas/reels-v1.schema.json` describes the normalized, versioned collection.+The importer constructs an allowlist of fields: unknown properties, provider+payloads, media URLs, thumbnails, cookies and local paths are not retained.+Known credential patterns in selected text are redacted. Lines containing+recognized filesystem paths are omitted conservatively, including trailing text.+Pattern matching cannot identify every secret in arbitrary prose: producers+must export public content, never credentials embedded in captions/transcripts.++Only HTTPS `instagram.com` and `www.instagram.com` post/reel URLs are accepted;+credentials, custom ports, profile links and lookalike hosts are rejected. URLs+become `https://www.instagram.com/p/<shortcode>/` without query or fragment.+The source is validated locally; no URL or media is fetched during import.++Unknown, nonnumeric, negative or nonfinite metrics become `null`; zero remains+zero. Plays and views are independent. Invalid or absent dates become `null`.+States normalize to `classified`, `unclassified`, `excluded`, or `error`.+`needsReview` is derived from labels/anatomy: confidence below 0.65, an `unclear`+value, or missing anatomy confidence requires review. It is not evidence of+human approval and cannot be overridden by a raw `needsReview: false` field.++Library IDs hash the lowercase creator plus source collection ID. Item IDs+are preserved, independent of URL aliases and filenames. Identical duplicate+item IDs collapse; conflicting duplicates reject the whole import. Posts are+sorted by ID. Reimporting replaces that collection atomically, not appends to+it; items omitted from a replacement snapshot disappear. The last successful+atomic write wins. No import timestamp is injected, so identical inputs produce+identical normalized content. `sourceId` retains the original collection ID.++Storage is `reels/v1/<library-id>.json` below the isolated Jev Social state+directory (`~/.jev-social` by default, or `JEV_SOCIAL_HOME`). Storage inside this+checkout and symlinked state/library directories is rejected. Files are written+privately via a temporary file and atomic rename. Reads revalidate the schema+and identity, enforce the size limit, and skip malformed/unsafe entries.+Nothing is stored in or served from `public/`.++`filterReels` filters normalized posts by topic, hook (`mechanism`), structure,+confidence and review/status. Confidence thresholds apply to the selected+dimension and every active label filter. The function preserves null metrics+and does not infer engagement effects, causality, or popularity rankings.++## Verification++Run `npm run check` and `npm test`. Focused tests cover normalization, malformed+input, unsafe URLs, privacy, duplicate IDs, filtering, atomic replacement and+reopening a collection after stopping and recreating the HTTP server. Tests use+temporary state directories and no social accounts or model calls.diff --git a/package.json b/package.jsonindex 00d934c..56289e5 100644--- a/package.json+++ b/package.json@@ -31,9 +31,12 @@"benchmark/tasks/linkedin.json","benchmark/tasks/tiktok.json","bin",+ "docs/reels-import.md",+ "docs/creator-lab-license.txt","docs/troubleshooting.md","public","skills",+ "schemas","src","README.md","LICENSE"@@ -43,7 +46,7 @@"dev": "node --watch ./bin/jev-social.js serve --no-open","benchmark:run": "node ./benchmark/run.js","benchmark:summarize": "node ./benchmark/summary.js",- "check": "node --check ./bin/jev-social.js && node --check ./benchmark/run.js && node --check ./benchmark/schema.js && node --check ./benchmark/summary.js && node --check ./scripts/verify-release.js && node --check ./src/server.js && node --check ./src/decision-provider.js && node --check ./src/evidence.js && node --check ./src/report.js && node --check ./public/app.js && node --check ./public/evidence-items.js && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/report-stream.js && node --check ./public/prompts.js && node --check ./public/status.js && node --check ./public/view-focus.js",+ "check": "node --check ./bin/jev-social.js && node --check ./benchmark/run.js && node --check ./benchmark/schema.js && node --check ./benchmark/summary.js && node --check ./scripts/verify-release.js && node --check ./src/server.js && node --check ./src/decision-provider.js && node --check ./src/evidence.js && node --check ./src/report.js && node --check ./public/app.js && node --check ./public/evidence-items.js && node --check ./public/evidence-preview.js && node --check ./public/run-route.js && node --check ./public/report-download.js && node --check ./public/report-stream.js && node --check ./public/prompts.js && node --check ./public/status.js && node --check ./public/view-focus.js && node --check ./src/reels.js && node --check ./src/reels-contract.js","test": "node --test"},"engines": {diff --git a/schemas/reels-v1.schema.json b/schemas/reels-v1.schema.jsonnew file mode 100644index 0000000..c52013e--- /dev/null+++ b/schemas/reels-v1.schema.json@@ -0,0 +1,531 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "urn:jev-social:reels:1",+ "title": "Jev Social normalized Reel collection v1",+ "description": "Normalized output. Runtime validation additionally enforces distinct IDs, ordered segment times, status/classification consistency and derived review state.",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schemaVersion",+ "id",+ "sourceId",+ "creator",+ "createdAt",+ "sourceStatus",+ "duplicateCount",+ "posts"+ ],+ "properties": {+ "schemaVersion": {+ "const": 1+ },+ "id": {+ "type": "string",+ "pattern": "^reels-[a-f0-9]{24}$"+ },+ "sourceId": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$"+ },+ "creator": {+ "type": "string",+ "pattern": "^[a-z0-9_.]{1,30}$"+ },+ "createdAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time"+ },+ "sourceStatus": {+ "enum": [+ "complete",+ "partial",+ "paused",+ "interrupted",+ "failed",+ "ready",+ "running",+ "scraping",+ "unknown"+ ]+ },+ "duplicateCount": {+ "type": "integer",+ "minimum": 0,+ "maximum": 999+ },+ "posts": {+ "type": "array",+ "minItems": 1,+ "maxItems": 1000,+ "items": {+ "$ref": "#/$defs/post"+ }+ }+ },+ "$defs": {+ "segment": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "text",+ "start",+ "end"+ ],+ "properties": {+ "text": {+ "type": "string",+ "maxLength": 48000+ },+ "start": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ },+ "end": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ }+ }+ },+ "analysis": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "labels",+ "anatomy"+ ],+ "properties": {+ "labels": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "topic",+ "opening",+ "mechanism",+ "structure",+ "evidence",+ "emotion",+ "specificity",+ "cta"+ ],+ "properties": {+ "topic": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "value",+ "confidence"+ ],+ "properties": {+ "value": {+ "enum": [+ "business",+ "money",+ "marketing",+ "mindset",+ "habits",+ "relationships",+ "health",+ "technology",+ "other",+ "unclear"+ ]+ },+ "confidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ }+ },+ "opening": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "value",+ "confidence"+ ],+ "properties": {+ "value": {+ "enum": [+ "question",+ "instruction",+ "claim",+ "story",+ "dialogue",+ "unclear"+ ]+ },+ "confidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ }+ },+ "mechanism": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "value",+ "confidence"+ ],+ "properties": {+ "value": {+ "enum": [+ "contradiction",+ "curiosity",+ "result",+ "mistake",+ "recognition",+ "story",+ "direct",+ "unclear"+ ]+ },+ "confidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ }+ },+ "structure": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "value",+ "confidence"+ ],+ "properties": {+ "value": {+ "enum": [+ "story",+ "steps",+ "problem_solution",+ "explanation",+ "comparison",+ "opinion",+ "qa",+ "unclear"+ ]+ },+ "confidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ }+ },+ "evidence": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "value",+ "confidence"+ ],+ "properties": {+ "value": {+ "enum": [+ "example",+ "personal",+ "numbers",+ "source",+ "reasoning",+ "none",+ "unclear"+ ]+ },+ "confidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ }+ },+ "emotion": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "value",+ "confidence"+ ],+ "properties": {+ "value": {+ "enum": [+ "aspiration",+ "concern",+ "relief",+ "surprise",+ "amusement",+ "neutral",+ "unclear"+ ]+ },+ "confidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ }+ },+ "specificity": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "value",+ "confidence"+ ],+ "properties": {+ "value": {+ "enum": [+ "none",+ "principle",+ "action",+ "sequence",+ "unclear"+ ]+ },+ "confidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ }+ },+ "cta": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "value",+ "confidence"+ ],+ "properties": {+ "value": {+ "enum": [+ "none",+ "follow",+ "engage",+ "comment",+ "visit",+ "buy",+ "multiple",+ "unclear"+ ]+ },+ "confidence": {+ "type": "number",+ "minimum": 0,+ "maximum": 1+ }+ }+ }+ }+ },+ "anatomy": {+ "type": "array",+ "maxItems": 200,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "text",+ "start",+ "end",+ "value",+ "confidence"+ ],+ "properties": {+ "text": {+ "type": "string",+ "maxLength": 48000+ },+ "start": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ },+ "end": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ },+ "value": {+ "enum": [+ "hook",+ "setup",+ "problem",+ "example",+ "advice",+ "payoff",+ "cta",+ "other",+ "unclear"+ ]+ },+ "confidence": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0,+ "maximum": 1+ }+ }+ }+ }+ }+ },+ "post": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "id",+ "url",+ "creator",+ "publishedAt",+ "capturedAt",+ "caption",+ "transcript",+ "duration",+ "plays",+ "views",+ "likes",+ "comments",+ "status",+ "statusNote",+ "analysis",+ "needsReview"+ ],+ "properties": {+ "id": {+ "type": "string",+ "pattern": "^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$"+ },+ "url": {+ "type": "string",+ "pattern": "^https://www\\.instagram\\.com/p/[A-Za-z0-9_-]+/$"+ },+ "creator": {+ "type": "string",+ "pattern": "^[a-z0-9_.]{1,30}$"+ },+ "publishedAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time"+ },+ "capturedAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time"+ },+ "caption": {+ "type": "string",+ "maxLength": 12000+ },+ "transcript": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "text",+ "segments"+ ],+ "properties": {+ "text": {+ "type": "string",+ "maxLength": 48000+ },+ "segments": {+ "type": "array",+ "maxItems": 200,+ "items": {+ "$ref": "#/$defs/segment"+ }+ }+ }+ },+ "duration": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ },+ "plays": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ },+ "views": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ },+ "likes": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ },+ "comments": {+ "type": [+ "number",+ "null"+ ],+ "minimum": 0+ },+ "status": {+ "enum": [+ "classified",+ "unclassified",+ "excluded",+ "error"+ ]+ },+ "statusNote": {+ "enum": [+ "",+ "No audio track",+ "Excluded by source",+ "Source processing failed"+ ]+ },+ "analysis": {+ "anyOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/$defs/analysis"+ }+ ]+ },+ "needsReview": {+ "type": "boolean"+ }+ }+ }+ }+}diff --git a/src/reels-contract.js b/src/reels-contract.jsnew file mode 100644index 0000000..754bfb3--- /dev/null+++ b/src/reels-contract.js@@ -0,0 +1,33 @@+// Creator Lab vocabulary; see docs/creator-lab-license.txt.+export const REELS_SCHEMA_VERSION = 1;+export const MAX_REELS_BYTES = 10_000_000;+export const REVIEW_THRESHOLD = 0.65;+export const LABEL_VALUES = {+ topic: ["business", "money", "marketing", "mindset", "habits", "relationships", "health", "technology", "other", "unclear"],+ opening: ["question", "instruction", "claim", "story", "dialogue", "unclear"],+ mechanism: ["contradiction", "curiosity", "result", "mistake", "recognition", "story", "direct", "unclear"],+ structure: ["story", "steps", "problem_solution", "explanation", "comparison", "opinion", "qa", "unclear"],+ evidence: ["example", "personal", "numbers", "source", "reasoning", "none", "unclear"],+ emotion: ["aspiration", "concern", "relief", "surprise", "amusement", "neutral", "unclear"],+ specificity: ["none", "principle", "action", "sequence", "unclear"],+ cta: ["none", "follow", "engage", "comment", "visit", "buy", "multiple", "unclear"],+};+export const SCRIPT_ROLES = ["hook", "setup", "problem", "example", "advice", "payoff", "cta", "other", "unclear"];+export const SOURCE_STATES = ["complete", "partial", "paused", "interrupted", "failed", "ready", "running", "scraping", "unknown"];+export const knownMetric = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;++export function filterReels(posts, { topic = "all", mechanism = "all", structure = "all", review = "all", minConfidence = 0, dimension = "mechanism" } = {}) {+ if (!knownMetric(minConfidence) || minConfidence > 1 || !Object.hasOwn(LABEL_VALUES, dimension)) throw new Error("Invalid classification filter.");+ if (!["all", "review", "classified", "unclassified", "excluded", "error"].includes(review)) throw new Error("Invalid review filter.");+ const selected = { topic, mechanism, structure };+ for (const [key, value] of Object.entries(selected)) {+ if (value !== "all" && !LABEL_VALUES[key].includes(value)) throw new Error("Invalid classification filter.");+ }+ const dimensions = new Set([dimension, ...Object.keys(selected).filter((key) => selected[key] !== "all")]);+ return posts.filter((post) => {+ if (review === "review" && !post.needsReview) return false;+ if (review !== "all" && review !== "review" && post.status !== review) return false;+ if (Object.entries(selected).some(([key, value]) => value !== "all" && post.analysis?.labels[key]?.value !== value)) return false;+ return !minConfidence || [...dimensions].every((key) => post.analysis?.labels[key]?.confidence >= minConfidence);+ });+}diff --git a/src/reels.js b/src/reels.jsnew file mode 100644index 0000000..49f444e--- /dev/null+++ b/src/reels.js@@ -0,0 +1,206 @@+import crypto from "node:crypto";+import { constants } from "node:fs";+import { lstat, mkdir, open, readdir, realpath, rename, unlink, writeFile } from "node:fs/promises";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { getHomeDir } from "./config.js";+import { AppError } from "./errors.js";+import { LABEL_VALUES, MAX_REELS_BYTES, REELS_SCHEMA_VERSION, REVIEW_THRESHOLD, SCRIPT_ROLES, SOURCE_STATES, knownMetric } from "./reels-contract.js";++const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);+const stableId = (value) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value);+const libraryId = (value) => typeof value === "string" && /^reels-[a-f0-9]{24}$/.test(value);+const invalid = (message) => new AppError(message, { code: "INVALID_REELS_IMPORT" });+const metric = (value) => knownMetric(value) ? value : null;+const datePattern = /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])[Tt](?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;+const creatorName = (value) => typeof value === "string" && /^[a-zA-Z0-9_.]{1,30}$/.test(value);++function date(value) {+ const match = typeof value === "string" ? datePattern.exec(value) : null;+ if (!match) return null;+ const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]);+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];+ const timestamp = day <= days[month - 1] ? Date.parse(value) : NaN;+ return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;+}++function redactPaths(value) {+ // Drop the whole line when a local path is detected, including paths with+ // spaces. Scan bounded lines/tokens without nested, overlapping quantifiers.+ return value.split(/\r?\n/).map((line) => {+ const absolute = /(^|[\s("'`=:])(?:file:\/\/\/|[A-Za-z]:[\\/]|\\\\|~[\\/]|\.{1,2}[\\/]|\/(?!\/))\S/.test(line);+ const named = /\b(?:run_dir|local_path|output_dir|artifact_path|report_path)\s*[:=]/i.test(line);+ const relative = line.split(/\s+/).some((token) => token.includes("/") && !token.includes("://") && /\.[A-Za-z0-9]{1,10}[),;:!?\]}"']*$/.test(token));+ return absolute || named || relative ? "[redacted path]" : line;+ }).join("\n");+}++function text(value, max = 12000) {+ if (value == null) return "";+ if (typeof value !== "string" || value.length > max) throw invalid("Invalid or oversized Reel text field.");+ return redactPaths(value)+ .replace(/\b(?:authorization|cookie|set-cookie|(?:access[_ -]?|refresh[_ -]?|session[_ -]?)?token|api[_ -]?key|password|secret)\s*[:=]\s*[^\r\n]*/gi, "[redacted credential]")+ .replace(/\bBearer\s+[A-Za-z0-9._~+\/-]+=*/gi, "[redacted credential]")+ .replace(/\b(?:sk-|gsk_|apify_api_|gh[pousr]_|github_pat_)[A-Za-z0-9_-]{8,}\b/g, "[redacted credential]")+ .replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g, "[redacted credential]")+ .replace(/data:[^\s]+/gi, "[media omitted]").slice(0, max);+}++function source(raw) {+ if (typeof raw !== "string" || raw.length > 5000) throw invalid("Every Reel needs a valid Instagram post URL.");+ let url;+ try { url = new URL(raw); } catch { throw invalid("Every Reel needs a valid Instagram post URL."); }+ const code = url.pathname.match(/^\/(?:p|reel)\/([A-Za-z0-9_-]+)\/?$/)?.[1];+ if (!code || url.protocol !== "https:" || url.username || url.password || url.port+ || !["instagram.com", "www.instagram.com"].includes(url.hostname)) throw invalid("Every Reel needs a valid Instagram post URL.");+ return `https://www.instagram.com/p/${code}/`;+}++function segments(raw = [], labeled = false) {+ if (!Array.isArray(raw) || raw.length > 200) throw invalid("Invalid Reel transcript segments.");+ let previousStart = null;+ return raw.map((segment) => {+ if (!object(segment) || typeof segment.text !== "string") throw invalid("Invalid Reel transcript segment.");+ const start = segment.start ?? null, end = segment.end ?? null;+ if ((start !== null && !knownMetric(start)) || (end !== null && !knownMetric(end))+ || (start !== null && end !== null && end < start)+ || (start !== null && previousStart !== null && start < previousStart)) throw invalid("Invalid Reel segment timestamps.");+ if (start !== null) previousStart = start;+ const result = { text: text(segment.text, 48000), start, end };+ if (labeled) {+ if (!SCRIPT_ROLES.includes(segment.value)) throw invalid("Invalid Reel script role.");+ if (segment.confidence != null && (!knownMetric(segment.confidence) || segment.confidence > 1)) throw invalid("Invalid Reel segment confidence.");+ result.value = segment.value; result.confidence = segment.confidence ?? null;+ }+ return result;+ });+}++function classification(raw, transcript) {+ if (raw == null) return null;+ if (!object(raw) || !object(raw.labels) || !transcript) throw invalid("Classification requires labels and a transcript.");+ const labels = {};+ for (const [key, values] of Object.entries(LABEL_VALUES)) {+ const label = raw.labels[key];+ if (!object(label) || !values.includes(label.value) || !knownMetric(label.confidence) || label.confidence > 1) throw invalid("Invalid Reel classification or confidence.");+ labels[key] = { value: label.value, confidence: label.confidence };+ }+ return { labels, anatomy: segments(raw.anatomy, true) };+}++export function normalizeReels(raw) {+ if (!object(raw) || raw.schemaVersion !== REELS_SCHEMA_VERSION) throw invalid("Expected Reel import schemaVersion 1.");+ if (!stableId(raw.id) || !creatorName(raw.creator)) throw invalid("Invalid Reel collection ID or creator.");+ if (!Array.isArray(raw.posts) || !raw.posts.length || raw.posts.length > 1000) throw invalid("Import 1 to 1,000 Reel items.");+ if (raw.status != null && !SOURCE_STATES.includes(raw.status)) throw invalid("Invalid Reel collection status.");+ const creator = raw.creator.toLowerCase(), seen = new Map(), posts = [];+ for (const item of raw.posts) {+ if (!object(item) || !stableId(item.id)) throw invalid("Every Reel needs a stable item ID.");+ if (item.creator != null && !creatorName(item.creator)) throw invalid("Invalid Reel creator.");+ if (item.status != null && !["classified", "unclassified", "pending", "ready", "no_audio", "no_speech", "excluded", "failed", "error"].includes(item.status)) throw invalid("Invalid Reel item status.");+ if (item.transcript != null && !object(item.transcript)) throw invalid("Invalid Reel transcript.");+ const transcript = { text: text(item.transcript?.text, 48000), segments: segments(item.transcript?.segments) };+ const analysis = classification(item.analysis, transcript.text);+ if (item.excludedReason != null && typeof item.excludedReason !== "string") throw invalid("Invalid Reel exclusion reason.");+ const excluded = Boolean(item.excludedReason) || ["no_audio", "no_speech", "excluded"].includes(item.status);+ const failed = ["failed", "error"].includes(item.status);+ if (excluded && failed) throw invalid("A Reel cannot be both excluded and failed.");+ if ((excluded || failed) && analysis) throw invalid("Excluded or error rows cannot contain a classification.");+ if (item.status === "classified" && !analysis) throw invalid("Classified rows require a classification.");+ const status = excluded ? "excluded" : failed ? "error" : analysis ? "classified" : "unclassified";+ const post = {+ id: item.id, url: source(item.url), creator: (item.creator || creator).toLowerCase(),+ publishedAt: date(item.publishedAt), capturedAt: date(item.capturedAt || item.scrapedAt),+ caption: text(item.caption), transcript, duration: metric(item.duration),+ plays: metric(item.plays), views: metric(item.views), likes: metric(item.likes), comments: metric(item.comments),+ status, statusNote: excluded ? (item.status === "no_audio" || item.statusNote === "No audio track" ? "No audio track" : "Excluded by source") : failed ? "Source processing failed" : "",+ analysis, needsReview: Boolean(analysis) && (Object.values(analysis.labels).some((label) => label.confidence < REVIEW_THRESHOLD || label.value === "unclear")+ || analysis.anatomy.some((segment) => segment.confidence === null || segment.confidence < REVIEW_THRESHOLD || segment.value === "unclear")),+ };+ const duplicate = seen.get(post.id);+ if (duplicate && JSON.stringify(duplicate) !== JSON.stringify(post)) throw invalid("Conflicting duplicate Reel item IDs.");+ if (!duplicate) { seen.set(post.id, post); posts.push(post); }+ }+ posts.sort((a, b) => a.id.localeCompare(b.id, "en"));+ return {+ schemaVersion: REELS_SCHEMA_VERSION,+ id: `reels-${crypto.createHash("sha256").update(`${creator}\0${raw.id}`).digest("hex").slice(0, 24)}`,+ sourceId: raw.id, creator, createdAt: date(raw.createdAt), sourceStatus: raw.status || "unknown",+ duplicateCount: raw.posts.length - posts.length, posts,+ };+}++async function directory(env, create = false) {+ const root = getHomeDir(env);+ const project = await realpath(fileURLToPath(new URL("..", import.meta.url)));+ const insideProject = (candidate) => {+ const relative = path.relative(project, candidate);+ return !relative || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));+ };+ if (insideProject(root)) throw new Error("Reel storage must be outside the project.");+ if (create) await mkdir(root, { recursive: true, mode: 0o700 });+ if ((await lstat(root)).isSymbolicLink()) throw new Error("State directory must not be a symlink.");+ if (insideProject(await realpath(root))) throw new Error("Reel storage must be outside the project.");+ let result = root;+ for (const name of ["reels", "v1"]) {+ result = path.join(result, name);+ if (create) await mkdir(result, { mode: 0o700 }).catch((error) => { if (error.code !== "EEXIST") throw error; });+ const info = await lstat(result);+ if (info.isSymbolicLink() || !info.isDirectory()) throw new Error("Invalid Reel storage directory.");+ }+ return result;+}++export async function importReels(raw, env = process.env) {+ let bytes;+ try { bytes = Buffer.byteLength(JSON.stringify(raw)); } catch { throw invalid("Invalid Reel JSON input."); }+ if (bytes > MAX_REELS_BYTES) throw invalid("Reel imports must not exceed 10 MB.");+ const collection = normalizeReels(raw), serialized = JSON.stringify(collection);+ if (Buffer.byteLength(serialized) > MAX_REELS_BYTES) throw invalid("Normalized Reel imports must not exceed 10 MB.");+ let temporary;+ try {+ const root = await directory(env, true);+ temporary = path.join(root, `${collection.id}.${crypto.randomUUID()}.tmp`);+ await writeFile(temporary, serialized, { flag: "wx", mode: 0o600 });+ await rename(temporary, path.join(root, `${collection.id}.json`));+ } catch { throw new AppError("The local library could not save this collection.", { code: "REELS_SAVE_FAILED", status: 500 }); }+ finally { if (temporary) await unlink(temporary).catch(() => {}); }+ return collection;+}++export async function readReels(id, env = process.env) {+ if (!libraryId(id)) return null;+ let file;+ try {+ file = await open(path.join(await directory(env), `${id}.json`), constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | (constants.O_NONBLOCK || 0));+ const info = await file.stat();+ if (!info.isFile() || info.size > MAX_REELS_BYTES) return null;+ const chunks = []; let bytes = 0;+ for await (const chunk of file.createReadStream({ autoClose: false })) {+ bytes += chunk.length; if (bytes > MAX_REELS_BYTES) return null;+ chunks.push(chunk);+ }+ const saved = JSON.parse(Buffer.concat(chunks).toString("utf8"));+ const clean = normalizeReels({ ...saved, id: saved.sourceId, status: saved.sourceStatus });+ if (clean.id !== id || saved.id !== id) return null;+ if (!Number.isInteger(saved.duplicateCount) || saved.duplicateCount < 0 || saved.duplicateCount > 999) return null;+ return { ...clean, duplicateCount: saved.duplicateCount };+ } catch { return null; }+ finally { await file?.close(); }+}++export async function listReels(env = process.env) {+ let files;+ try { files = await readdir(await directory(env)); }+ catch (error) {+ if (error.code === "ENOENT") return [];+ throw new AppError("The local library could not read saved collections.", { code: "REELS_READ_FAILED", status: 500 });+ }+ const collections = [];+ for (const name of files.filter((name) => /^reels-[a-f0-9]{24}\.json$/.test(name)).sort()) {+ const saved = await readReels(name.slice(0, -5), env);+ if (saved) collections.push({ id: saved.id, sourceId: saved.sourceId, schemaVersion: saved.schemaVersion, creator: saved.creator, sourceStatus: saved.sourceStatus, itemCount: saved.posts.length });+ }+ return collections;+}diff --git a/src/server.js b/src/server.jsindex a2bbc04..759862e 100644--- a/src/server.js+++ b/src/server.js@@ -15,6 +15,8 @@ import { loadLocalEnv } from "./env.js";import { saveOnboarding } from "./onboard.js";import { listRuns, markInterruptedRuns, readRun } from "./runs.js";import { probeSocai, unknownSocaiReadiness } from "./socai.js";+import { importReels, listReels, readReels } from "./reels.js";+import { MAX_REELS_BYTES } from "./reels-contract.js";const PUBLIC_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../public");const MEDIA_TTL_MS = 60 * 60_000;@@ -158,6 +160,19 @@ async function handleRequest(request, response, env, mediaRegistry) {validateSearchBody(body);return streamSearch(request, response, body, env, mediaRegistry);}+ if (request.method === "POST" && url.pathname === "/api/reels") {+ assertSameOrigin(request);+ return sendJson(response, 201, await importReels(await readJson(request, MAX_REELS_BYTES), env));+ }+ if (request.method === "GET" && url.pathname === "/api/reels") {+ return sendJson(response, 200, { collections: await listReels(env) });+ }+ const reelsMatch = request.method === "GET" && url.pathname.match(/^\/api\/reels\/(reels-[a-f0-9]{24})$/);+ if (reelsMatch) {+ const collection = await readReels(reelsMatch[1], env);+ return collection ? sendJson(response, 200, collection)+ : sendJson(response, 404, { error: { code: "REELS_NOT_FOUND", message: "Collection not found." } });+ }if (request.method === "GET" && url.pathname === "/api/runs") {return sendJson(response, 200, { runs: await listRuns(env) });}@@ -390,7 +405,7 @@ function assertSameOrigin(request) {}}-async function readJson(request) {+async function readJson(request, maxBytes = 1_000_000) {const contentType = request.headers["content-type"]?.split(";", 1)[0].trim().toLowerCase();if (contentType !== "application/json") {throw httpError(415, "UNSUPPORTED_MEDIA_TYPE", "Content-Type must be application/json.");@@ -399,7 +414,7 @@ async function readJson(request) {let size = 0;for await (const chunk of request) {size += chunk.length;- if (size > 1_000_000) {+ if (size > maxBytes) {throw httpError(413, "BODY_TOO_LARGE", "Request body is too large.");}chunks.push(chunk);diff --git a/test/fixtures/reels-import-v1.json b/test/fixtures/reels-import-v1.jsonnew file mode 100644index 0000000..5dce7b9--- /dev/null+++ b/test/fixtures/reels-import-v1.json@@ -0,0 +1,179 @@+{+ "schemaVersion": 1,+ "id": "fixture-collection-1",+ "creator": "Example",+ "createdAt": "2026-09-03T12:00:00Z",+ "status": "partial",+ "posts": [+ {+ "id": "item-a",+ "url": "https://instagram.com/reel/FixtureA/?utm_source=fixture",+ "caption": "A synthetic marketing example.",+ "publishedAt": "2026-09-01T12:00:00Z",+ "capturedAt": "2026-09-03T12:00:00Z",+ "plays": 1000,+ "views": null,+ "likes": 20,+ "comments": 0,+ "transcript": {+ "text": "Build one useful thing. Show your work.",+ "segments": [+ {+ "text": "Build one useful thing.",+ "start": 0,+ "end": 2.5+ },+ {+ "text": "Show your work.",+ "start": 2.5,+ "end": 5+ }+ ]+ },+ "analysis": {+ "labels": {+ "topic": {+ "value": "marketing",+ "confidence": 0.9+ },+ "opening": {+ "value": "question",+ "confidence": 0.9+ },+ "mechanism": {+ "value": "curiosity",+ "confidence": 0.9+ },+ "structure": {+ "value": "steps",+ "confidence": 0.9+ },+ "evidence": {+ "value": "example",+ "confidence": 0.9+ },+ "emotion": {+ "value": "aspiration",+ "confidence": 0.9+ },+ "specificity": {+ "value": "none",+ "confidence": 0.9+ },+ "cta": {+ "value": "none",+ "confidence": 0.9+ }+ },+ "anatomy": [+ {+ "text": "Build one useful thing.",+ "start": 0,+ "end": 2.5,+ "value": "hook",+ "confidence": 0.9+ }+ ]+ }+ },+ {+ "id": "item-b",+ "url": "https://www.instagram.com/p/FixtureB/",+ "status": "no_audio",+ "plays": null,+ "views": 500+ },+ {+ "id": "item-c",+ "url": "https://www.instagram.com/p/FixtureC/",+ "status": "failed",+ "error": "provider details must not be retained"+ },+ {+ "id": "item-d",+ "url": "https://www.instagram.com/p/FixtureD/",+ "transcript": {+ "text": "Unclassified synthetic speech.",+ "segments": [+ {+ "text": "Unclassified synthetic speech.",+ "start": null,+ "end": null+ }+ ]+ },+ "likes": 0+ },+ {+ "id": "item-e",+ "url": "https://www.instagram.com/p/FixtureE/",+ "caption": "A synthetic marketing example.",+ "publishedAt": "2026-09-01T12:00:00Z",+ "capturedAt": "2026-09-03T12:00:00Z",+ "plays": null,+ "views": 400,+ "likes": 20,+ "comments": 0,+ "transcript": {+ "text": "Build one useful thing. Show your work.",+ "segments": [+ {+ "text": "Build one useful thing.",+ "start": 0,+ "end": 2.5+ },+ {+ "text": "Show your work.",+ "start": 2.5,+ "end": 5+ }+ ]+ },+ "analysis": {+ "labels": {+ "topic": {+ "value": "marketing",+ "confidence": 0.9+ },+ "opening": {+ "value": "question",+ "confidence": 0.9+ },+ "mechanism": {+ "value": "unclear",+ "confidence": 0.3+ },+ "structure": {+ "value": "steps",+ "confidence": 0.9+ },+ "evidence": {+ "value": "example",+ "confidence": 0.9+ },+ "emotion": {+ "value": "aspiration",+ "confidence": 0.9+ },+ "specificity": {+ "value": "none",+ "confidence": 0.9+ },+ "cta": {+ "value": "none",+ "confidence": 0.9+ }+ },+ "anatomy": [+ {+ "text": "Build one useful thing.",+ "start": 0,+ "end": 2.5,+ "value": "hook",+ "confidence": 0.9+ }+ ]+ }+ }+ ]+}diff --git a/test/npm-publish-workflow.test.js b/test/npm-publish-workflow.test.jsindex 9c91f34..dc23852 100644--- a/test/npm-publish-workflow.test.js+++ b/test/npm-publish-workflow.test.js@@ -154,6 +154,8 @@ test("the npm tarball has one reviewed file set and no bundled dependencies", ()"benchmark/tasks/linkedin.json","benchmark/tasks/tiktok.json","bin/jev-social.js",+ "docs/creator-lab-license.txt",+ "docs/reels-import.md","docs/troubleshooting.md","package.json","public/app.js",@@ -170,6 +172,7 @@ test("the npm tarball has one reviewed file set and no bundled dependencies", ()"public/status.js","public/styles.css","public/view-focus.js",+ "schemas/reels-v1.schema.json","skills/jev-social/agents/openai.yaml","skills/jev-social/SKILL.md","src/actions.js",@@ -184,6 +187,8 @@ test("the npm tarball has one reviewed file set and no bundled dependencies", ()"src/onboard.js","src/process.js","src/query.js",+ "src/reels-contract.js",+ "src/reels.js","src/report.js","src/runs.js","src/server.js",diff --git a/test/reels-server.test.js b/test/reels-server.test.jsnew file mode 100644index 0000000..1759851--- /dev/null+++ b/test/reels-server.test.js@@ -0,0 +1,64 @@+import assert from "node:assert/strict";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import test from "node:test";+import { MAX_REELS_BYTES } from "../src/reels-contract.js";+import { startServer } from "../src/server.js";++const fixture = JSON.parse(await readFile(new URL("fixtures/reels-import-v1.json", import.meta.url), "utf8"));+const close = (server) => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));+const post = (url, body, headers = {}) => fetch(`${url}/api/reels`, {+ method: "POST", headers: { Origin: url, "Content-Type": "application/json", ...headers }, body,+});++test("Reel API imports without credentials and reopens the same collection after server restart", async (t) => {+ const root = await mkdtemp(path.join(os.tmpdir(), "jev-reels-server-"));+ t.after(() => rm(root, { recursive: true, force: true }));+ const env = { JEV_SOCIAL_HOME: path.join(root, "state"), PATH: "", SOCAI_BIN: path.join(root, "no-socai-installed") };+ let running = await startServer({ port: 0, open: false, env });+ t.after(() => close(running.server));+ assert.deepEqual(await (await fetch(`${running.url}/api/reels`)).json(), { collections: [] });+ const response = await post(running.url, JSON.stringify(fixture));+ assert.equal(response.status, 201);+ const saved = await response.json();+ assert.equal(saved.posts.length, 5);+ assert.doesNotMatch(JSON.stringify(saved), new RegExp(root));+ await close(running.server);+ running = await startServer({ port: 0, open: false, env });+ const reopened = await fetch(`${running.url}/api/reels/${saved.id}`);+ assert.equal(reopened.status, 200);+ assert.deepEqual(await reopened.json(), saved);+ const list = await (await fetch(`${running.url}/api/reels`)).json();+ assert.deepEqual(list.collections, [{ id: saved.id, sourceId: saved.sourceId, schemaVersion: 1, creator: "example", sourceStatus: "partial", itemCount: 5 }]);+ const repeat = await post(running.url, JSON.stringify({ ...fixture, filename: "renamed.json" }));+ assert.equal(repeat.status, 201);+ assert.deepEqual(await repeat.json(), saved);+ const invalid = await post(running.url, JSON.stringify({ ...fixture, schemaVersion: 2 }));+ assert.equal(invalid.status, 400);+ assert.deepEqual(await (await fetch(`${running.url}/api/reels/${saved.id}`)).json(), saved);+ const missing = await fetch(`${running.url}/api/reels/reels-${"0".repeat(24)}`);+ assert.equal(missing.status, 404);+ assert.equal((await missing.json()).error.code, "REELS_NOT_FOUND");+ assert.equal((await fetch(`${running.url}/`)).status, 200);+});++test("Reel API rejects cross-origin, malformed, unsafe and oversized imports without writing data", async (t) => {+ const root = await mkdtemp(path.join(os.tmpdir(), "jev-reels-http-"));+ const env = { JEV_SOCIAL_HOME: root, PATH: "", SOCAI_BIN: path.join(root, "no-socai-installed") };+ const { server, url } = await startServer({ port: 0, open: false, env });+ t.after(async () => { await close(server); await rm(root, { recursive: true, force: true }); });+ for (const headers of [{ Origin: "" }, { Origin: "https://example.test" }, { Origin: "http://127.0.0.1:9" }]) {+ assert.equal((await post(url, JSON.stringify(fixture), headers)).status, 403);+ }+ assert.equal((await post(url, "{}", { "Content-Type": "text/plain" })).status, 415);+ assert.equal((await post(url, "{")).status, 400);+ assert.equal((await post(url, "null")).status, 400);+ const unsafe = structuredClone(fixture); unsafe.posts[0].url = "https://evil.test/private";+ const invalid = await post(url, JSON.stringify(unsafe));+ assert.equal(invalid.status, 400);+ assert.equal((await invalid.json()).error.code, "INVALID_REELS_IMPORT");+ const oversized = await post(url, JSON.stringify({ ignored: "x".repeat(MAX_REELS_BYTES) }));+ assert.equal(oversized.status, 413);+ assert.deepEqual(await (await fetch(`${url}/api/reels`)).json(), { collections: [] });+});diff --git a/test/reels.test.js b/test/reels.test.jsnew file mode 100644index 0000000..4e8f329--- /dev/null+++ b/test/reels.test.js@@ -0,0 +1,294 @@+import assert from "node:assert/strict";+import { lstat, mkdir, mkdtemp, readFile, readdir, rm, symlink, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import test from "node:test";+import { filterReels, LABEL_VALUES, MAX_REELS_BYTES, SCRIPT_ROLES, SOURCE_STATES } from "../src/reels-contract.js";+import { importReels, listReels, normalizeReels, readReels } from "../src/reels.js";++const sample = JSON.parse(await readFile(new URL("fixtures/reels-import-v1.json", import.meta.url), "utf8"));+const fixture = () => structuredClone(sample);+const ids = (posts) => posts.map((post) => post.id);+async function storage(t) {+ const root = await mkdtemp(path.join(os.tmpdir(), "jev-reels-"));+ t.after(() => rm(root, { recursive: true, force: true }));+ const env = { JEV_SOCIAL_HOME: path.join(root, "state") };+ return { root, env, directory: path.join(env.JEV_SOCIAL_HOME, "reels", "v1") };+}++test("v1 fixture preserves transcripts, independent nullable metrics and explicit states", () => {+ const result = normalizeReels(fixture());+ assert.match(result.id, /^reels-[a-f0-9]{24}$/);+ assert.equal(result.schemaVersion, 1);+ assert.equal(result.sourceId, "fixture-collection-1");+ assert.equal(result.creator, "example");+ assert.equal(result.sourceStatus, "partial");+ assert.equal(result.createdAt, "2026-09-03T12:00:00.000Z");+ assert.equal(result.duplicateCount, 0);+ const [a, b, c, d, e] = result.posts;+ assert.equal(a.url, "https://www.instagram.com/p/FixtureA/");+ assert.deepEqual(a.transcript, sample.posts[0].transcript);+ assert.deepEqual(a.analysis, sample.posts[0].analysis);+ assert.equal(a.plays, 1000);+ assert.equal(a.views, null);+ assert.equal(a.comments, 0);+ assert.equal(b.plays, null);+ assert.equal(b.views, 500);+ assert.deepEqual(result.posts.map((post) => post.status), ["classified", "excluded", "error", "unclassified", "classified"]);+ assert.equal(b.statusNote, "No audio track");+ assert.equal(c.statusNote, "Source processing failed");+ assert.equal(d.transcript.segments[0].start, null);+ assert.equal(d.likes, 0);+ assert.deepEqual(result.posts.map((post) => post.needsReview), [false, false, false, false, true]);+ assert.equal(e.analysis.labels.mechanism.confidence, 0.3);+});++test("IDs are independent of filenames, input order, creator case and source URL aliases", () => {+ const raw = fixture(), original = normalizeReels(raw);+ raw.filename = "renamed-export.json";+ raw.creator = "EXAMPLE";+ raw.posts.reverse();+ raw.posts.find((post) => post.id === "item-a").url = "https://www.instagram.com/p/FixtureA/#ignored";+ assert.deepEqual(normalizeReels(raw), original);+ raw.posts.push(structuredClone(raw.posts[0]));+ assert.deepEqual(normalizeReels(raw).posts, original.posts);+ assert.equal(normalizeReels(raw).duplicateCount, 1);+ raw.posts.at(-1).caption = "A conflicting snapshot.";+ assert.throws(() => normalizeReels(raw), /Conflicting duplicate/);+ assert.notEqual(normalizeReels({ ...fixture(), id: "other" }).id, original.id);+ assert.notEqual(normalizeReels({ ...fixture(), creator: "another" }).id, original.id);+});++test("malformed envelopes, classifications and timestamps fail closed", () => {+ const changes = [+ (raw) => delete raw.schemaVersion,+ (raw) => raw.schemaVersion = 2,+ (raw) => raw.id = "../escape",+ (raw) => raw.creator = "@invalid",+ (raw) => raw.status = "invented",+ (raw) => raw.posts = [],+ (raw) => raw.posts = Array(1001).fill(raw.posts[0]),+ (raw) => raw.posts[0].id = "../../escape",+ (raw) => raw.posts[0].creator = "/Users/private",+ (raw) => raw.posts[0].status = "invented",+ (raw) => raw.posts[0].status = "failed",+ (raw) => raw.posts[1].status = "classified",+ (raw) => raw.posts[1].excludedReason = {},+ (raw) => raw.posts[2].excludedReason = "also excluded",+ (raw) => raw.posts[0].transcript = "raw text",+ (raw) => raw.posts[0].transcript.text = "",+ (raw) => raw.posts[0].caption = {},+ (raw) => raw.posts[0].caption = "x".repeat(12001),+ (raw) => raw.posts[0].transcript.text = "x".repeat(48001),+ (raw) => raw.posts[0].transcript.segments = Array(201).fill({}),+ (raw) => raw.posts[0].transcript.segments = [null],+ (raw) => raw.posts[0].transcript.segments.reverse(),+ (raw) => delete raw.posts[0].transcript.segments[0].text,+ (raw) => raw.posts[0].transcript.segments[0].start = -1,+ (raw) => raw.posts[0].transcript.segments[0].start = "0",+ (raw) => raw.posts[0].transcript.segments[0].end = Infinity,+ (raw) => raw.posts[0].transcript.segments[0].end = -1,+ (raw) => raw.posts[0].transcript.segments[1].end = 1,+ (raw) => delete raw.posts[0].analysis.labels.topic,+ (raw) => raw.posts[0].analysis.labels.topic.value = "invented",+ (raw) => raw.posts[0].analysis.labels.topic.confidence = "0.9",+ (raw) => raw.posts[0].analysis.labels.topic.confidence = 1.01,+ (raw) => raw.posts[0].analysis.labels.topic.confidence = NaN,+ (raw) => raw.posts[0].analysis.anatomy[0].value = "invented",+ (raw) => raw.posts[0].analysis.anatomy[0].confidence = -0.1,+ ];+ for (const change of changes) {+ const raw = fixture(); change(raw);+ assert.throws(() => normalizeReels(raw), { code: "INVALID_REELS_IMPORT" }, change.toString());+ }+ for (const raw of [null, [], "text", 1]) assert.throws(() => normalizeReels(raw), { code: "INVALID_REELS_IMPORT" });+});++test("dates require an explicit timezone and normalize offsets deterministically", () => {+ const raw = fixture();+ raw.createdAt = "2026-09-03T12:00:00";+ raw.posts[0].publishedAt = "2026-09-01T12:00:00";+ raw.posts[0].capturedAt = "2026-09-03T12:00:00+08:00";+ raw.posts[1].publishedAt = "2026-02-31T12:00:00Z";+ const result = normalizeReels(raw);+ assert.equal(result.createdAt, null);+ assert.equal(result.posts[0].publishedAt, null);+ assert.equal(result.posts[0].capturedAt, "2026-09-03T04:00:00.000Z");+ assert.equal(result.posts[1].publishedAt, null);+});++test("only HTTPS Instagram posts are accepted, without credentials or lookalike hosts", () => {+ for (const url of [+ "http://instagram.com/p/a/", "https://instagram.com.evil.test/p/a/",+ "https://evil.test/instagram.com/p/a/", "https://[email protected]/p/a/",+ "https://user:[email protected]/p/a/", "https://instagram.com:8443/p/a/",+ "https://instagram.com/profile/", "https://instagram.com/p/a/extra",+ "https://instagram.com/p/%2Fetc%2Fpasswd/", "javascript:alert(1)",+ "file:///tmp/post", "//instagram.com/p/a/", null,+ ]) {+ const raw = fixture(); raw.posts[0].url = url;+ assert.throws(() => normalizeReels(raw), { code: "INVALID_REELS_IMPORT" });+ }+});++test("unknown fields and known credential/path patterns never enter stored content", () => {+ const raw = fixture();+ raw[["api", "key"].join("_")] = "private-root-payload";+ raw.posts[0].providerResponse = { cookies: "private-provider-payload" };+ raw.posts[0].video = { local_path: "/Users/private/movie.mp4" };+ raw.posts[0].thumbnail = "https://cdn.example.test/private-poster";+ raw.posts[0].caption = "Public caption.\nAuthorization: Bearer private-token\n/Users/private/capture.json\n";+ raw.posts[0].transcript.segments[0].text = "api_key=private-segment-payload";+ raw.posts[0].analysis.anatomy[0].text = "data:video/mp4;base64,private-media-payload";+ const serialized = JSON.stringify(normalizeReels(raw));+ assert.match(serialized, /Public caption/);+ assert.match(serialized, /redacted credential/);+ assert.doesNotMatch(serialized, /private-|\/Users\/private|providerResponse|thumbnail|local_path/);+});++test("unknown counts stay null and review state is derived rather than trusted", () => {+ const raw = fixture(), a = raw.posts[0];+ a.plays = "1000"; a.views = -1; a.likes = NaN; a.comments = Infinity;+ a.publishedAt = "invalid";+ a.needsReview = false;+ a.analysis.anatomy[0].confidence = null;+ let post = normalizeReels(raw).posts[0];+ for (const key of ["plays", "views", "likes", "comments", "publishedAt"]) assert.equal(post[key], null);+ assert.equal(post.needsReview, true);+ a.analysis.anatomy[0].confidence = 0.65;+ a.analysis.labels.topic.confidence = 0.65;+ assert.equal(normalizeReels(raw).posts[0].needsReview, false);+ a.analysis.labels.topic.value = "unclear";+ assert.equal(normalizeReels(raw).posts[0].needsReview, true);+});++test("path sanitization handles dense paths and spaces without scanning across lines", () => {+ const raw = fixture();+ raw.posts[0].transcript.text = "/x ".repeat(8000);+ raw.posts[0].caption = "Public text.\n/Users/private/My Capture.json\nC:\\Users\\private\\My Capture.json\nrelative/capture.json\nhttps://www.instagram.com/p/FixtureA/";+ const post = normalizeReels(raw).posts[0];+ assert.equal(post.transcript.text, "[redacted path]");+ assert.equal(post.caption, "Public text.\n[redacted path]\n[redacted path]\n[redacted path]\nhttps://www.instagram.com/p/FixtureA/");+});++test("filters combine labels, confidence and review state without changing evidence", () => {+ const posts = normalizeReels(fixture()).posts, before = structuredClone(posts);+ assert.deepEqual(ids(filterReels(posts)), ["item-a", "item-b", "item-c", "item-d", "item-e"]);+ assert.deepEqual(ids(filterReels(posts, { topic: "marketing", structure: "steps" })), ["item-a", "item-e"]);+ assert.deepEqual(ids(filterReels(posts, { mechanism: "curiosity" })), ["item-a"]);+ assert.deepEqual(ids(filterReels(posts, { minConfidence: 0.65 })), ["item-a"]);+ assert.deepEqual(ids(filterReels(posts, { dimension: "topic", minConfidence: 0.65 })), ["item-a", "item-e"]);+ assert.deepEqual(ids(filterReels(posts, { dimension: "topic", mechanism: "unclear", minConfidence: 0.65 })), []);+ for (const [review, expected] of Object.entries({ review: ["item-e"], classified: ["item-a", "item-e"], excluded: ["item-b"], error: ["item-c"], unclassified: ["item-d"] })) {+ assert.deepEqual(ids(filterReels(posts, { review })), expected);+ }+ for (const options of [{ topic: "invented" }, { review: "invented" }, { minConfidence: "0" }, { minConfidence: 1.1 }, { dimension: "__proto__" }]) assert.throws(() => filterReels(posts, options));+ assert.deepEqual(posts, before);+});++test("schema vocabulary and closed field sets match the normalized fixture", async () => {+ const schema = JSON.parse(await readFile(new URL("../schemas/reels-v1.schema.json", import.meta.url), "utf8"));+ const collection = normalizeReels(fixture());+ function fields(value, definition) {+ assert.equal(definition.additionalProperties, false);+ assert.deepEqual(Object.keys(value).sort(), definition.required.toSorted());+ assert.deepEqual(Object.keys(value).sort(), Object.keys(definition.properties).sort());+ }+ fields(collection, schema);+ assert.deepEqual(schema.properties.sourceStatus.enum, SOURCE_STATES);+ for (const post of collection.posts) {+ fields(post, schema.$defs.post);+ fields(post.transcript, schema.$defs.post.properties.transcript);+ for (const segment of post.transcript.segments) fields(segment, schema.$defs.segment);+ if (post.analysis) {+ fields(post.analysis, schema.$defs.analysis);+ fields(post.analysis.labels, schema.$defs.analysis.properties.labels);+ for (const [key, values] of Object.entries(LABEL_VALUES)) {+ const label = schema.$defs.analysis.properties.labels.properties[key];+ fields(post.analysis.labels[key], label);+ assert.deepEqual(label.properties.value.enum, values);+ }+ }+ }+ assert.deepEqual(schema.$defs.analysis.properties.anatomy.items.properties.value.enum, SCRIPT_ROLES);+});++test("private atomic storage reopens exact data and replaces snapshots by stable identity", async (t) => {+ const { env, directory } = await storage(t);+ assert.deepEqual(await listReels(env), []);+ const raw = fixture(); raw.posts.push(structuredClone(raw.posts[0]));+ const saved = await importReels(raw, env), filename = path.join(directory, `${saved.id}.json`);+ assert.deepEqual(await readReels(saved.id, env), saved);+ const bytes = await readFile(filename, "utf8");+ await importReels({ ...raw, filename: "renamed.json" }, env);+ assert.equal(await readFile(filename, "utf8"), bytes);+ assert.deepEqual(await readdir(directory), [`${saved.id}.json`]);+ if (process.platform !== "win32") {+ assert.equal((await lstat(filename)).mode & 0o777, 0o600);+ for (const dir of [env.JEV_SOCIAL_HOME, path.dirname(directory), directory]) assert.equal((await lstat(dir)).mode & 0o777, 0o700);+ }+ const broken = fixture(); broken.posts[0].url = "file:///tmp/private";+ await assert.rejects(importReels(broken, env), { code: "INVALID_REELS_IMPORT" });+ assert.equal(await readFile(filename, "utf8"), bytes);+ const replacement = fixture(); replacement.posts = [replacement.posts[0]]; replacement.posts[0].plays = 2000;+ const updated = await importReels(replacement, env);+ assert.equal(updated.id, saved.id);+ assert.equal((await readReels(saved.id, env)).posts[0].plays, 2000);+ assert.equal((await listReels(env))[0].itemCount, 1);+});++test("bounded input and invalid storage fail without leaking local paths", async (t) => {+ const { root, env } = await storage(t);+ await assert.rejects(importReels({ ...fixture(), ignored: "x".repeat(MAX_REELS_BYTES) }, env), { code: "INVALID_REELS_IMPORT" });+ const expanding = { ...fixture(), posts: Array.from({ length: 220 }, (_, index) => ({+ id: `item-${index}`, url: `https://instagram.com/p/Fixture${index}/`, transcript: { text: "Bearer x ".repeat(4000) },+ })) };+ assert.ok(Buffer.byteLength(JSON.stringify(expanding)) < MAX_REELS_BYTES);+ await assert.rejects(importReels(expanding, env), /Normalized Reel imports must not exceed/);+ const cyclic = fixture(); cyclic.self = cyclic;+ await assert.rejects(importReels(cyclic, env), { code: "INVALID_REELS_IMPORT" });+ await assert.rejects(lstat(env.JEV_SOCIAL_HOME), { code: "ENOENT" });+ await writeFile(env.JEV_SOCIAL_HOME, "not a directory");+ await assert.rejects(importReels(fixture(), env), (error) => error.code === "REELS_SAVE_FAILED" && !error.message.includes(root));+ const project = fileURLToPath(new URL("../", import.meta.url));+ await assert.rejects(importReels(fixture(), { JEV_SOCIAL_HOME: path.join(project, "public", "forbidden-reels-state") }), { code: "REELS_SAVE_FAILED" });+ await assert.rejects(lstat(path.join(project, "public", "forbidden-reels-state")), { code: "ENOENT" });+});++test("corrupt, oversized, unsafe or mismatched persisted collections are not reopened", async (t) => {+ const { env, directory } = await storage(t);+ const saved = await importReels(fixture(), env), filename = path.join(directory, `${saved.id}.json`);+ const unsafe = structuredClone(saved); unsafe.posts[0].url = "https://evil.test/post";+ for (const content of ["{", "x".repeat(MAX_REELS_BYTES + 1), JSON.stringify({ ...saved, schemaVersion: 2 }), JSON.stringify({ ...saved, sourceId: "other" }), JSON.stringify({ ...saved, duplicateCount: -1 }), JSON.stringify(unsafe)]) {+ await writeFile(filename, content);+ assert.equal(await readReels(saved.id, env), null);+ assert.deepEqual(await listReels(env), []);+ }+ assert.equal(await readReels("../../outside", env), null);+ await rm(filename); await mkdir(filename);+ assert.equal(await readReels(saved.id, env), null);+});++test("symlinked state directories and saved files cannot expose outside content", { skip: process.platform === "win32" }, async (t) => {+ const { root, env, directory } = await storage(t);+ const outside = path.join(root, "outside"); await mkdir(outside);+ await symlink(outside, env.JEV_SOCIAL_HOME);+ await assert.rejects(importReels(fixture(), env), { code: "REELS_SAVE_FAILED" });+ await rm(env.JEV_SOCIAL_HOME); await mkdir(env.JEV_SOCIAL_HOME);+ await symlink(outside, path.join(env.JEV_SOCIAL_HOME, "reels"));+ await assert.rejects(importReels(fixture(), env), { code: "REELS_SAVE_FAILED" });+ await rm(path.join(env.JEV_SOCIAL_HOME, "reels"));+ await mkdir(path.join(env.JEV_SOCIAL_HOME, "reels"));+ await symlink(outside, directory);+ await assert.rejects(importReels(fixture(), env), { code: "REELS_SAVE_FAILED" });+ await rm(directory);+ const saved = await importReels(fixture(), env), filename = path.join(directory, `${saved.id}.json`);+ const target = path.join(outside, "outside.json"); await writeFile(target, JSON.stringify(saved));+ await rm(filename); await symlink(target, filename);+ assert.equal(await readReels(saved.id, env), null);+ assert.deepEqual(await listReels(env), []);+ await importReels(fixture(), env);+ assert.equal((await lstat(filename)).isSymbolicLink(), false);+ assert.equal(await readFile(target, "utf8"), JSON.stringify(saved));+});