前人工作区变更归档(元审计遗留处置·冰朔授权'交给你来处理'·不否定过去原则):hololake-phase-b-staging删除组/WORK区/submodule指针/0826壳源/neural-chain/skills-mirror/codex恢复帧/.zcode本地配置等140项原样冻结入库——不删除不修改不评判,作为历史一环保留;WX-SECRETS回执经查仅含公开AppID无AppSecret,安全

This commit is contained in:
冰朔 2026-09-01 22:18:31 +08:00
commit a40f29c12e
2442 changed files with 596545 additions and 6601 deletions

View file

@ -0,0 +1,344 @@
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
const CONTROL_ROOT = process.env.GH_CODEX_CONTROL_ROOT ??
"/Users/bingshuolingdianyuanhe/.codex/runtime/hldp-v1/control";
const CONTROLLER_PATH = path.join(CONTROL_ROOT, "current-controller.json");
const LEASE_SCRIPT = "/Users/bingshuolingdianyuanhe/.codex/runtime/hldp-v1/codex-write-lease.mjs";
const ANCHOR_GATE_SCRIPT = "/Users/bingshuolingdianyuanhe/.codex/runtime/hldp-v1/codex-task-anchor-gate.mjs";
const TASK_ANCHOR_ROOT = process.env.GH_CODEX_TASK_ANCHOR_ROOT ??
"/Volumes/JZAO/HoloLake/persona-runtime/task-language-anchors/codex";
function safeToken(value, fallback = "unknown") {
const token = String(value ?? "").trim().replaceAll(/[^a-zA-Z0-9._-]/gu, "-");
return token || fallback;
}
function sessionBindingPath(sessionId) {
return path.join(CONTROL_ROOT, "sessions", `${safeToken(sessionId)}.json`);
}
function channelControllerPath(channelId) {
return path.join(CONTROL_ROOT, "channels", safeToken(channelId), "controller.json");
}
function channelLeasePath(channelId) {
return path.join(CONTROL_ROOT, "channel-leases", safeToken(channelId), "write-lease.json");
}
function readInput() {
try {
const raw = fs.readFileSync(0, "utf8").trim();
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
}
function readJson(file) {
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
} catch {
return null;
}
}
function atomicWriteJson(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const temporary = `${file}.${process.pid}.tmp`;
fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
fs.renameSync(temporary, file);
}
function sha256(value) {
return crypto.createHash("sha256").update(value).digest("hex");
}
function allow(additionalContext = null) {
const value = additionalContext
? {
hookSpecificOutput: {
hookEventName: "PreToolUse",
additionalContext,
},
}
: { continue: true };
process.stdout.write(JSON.stringify(value));
}
function deny(reason) {
process.stdout.write(JSON.stringify({
hookSpecificOutput: {
hookEventName: "PreToolUse",
permissionDecision: "deny",
permissionDecisionReason: reason,
},
}));
}
function toolPayload(input) {
if (typeof input.tool_input === "string") return input.tool_input;
try {
return JSON.stringify(input.tool_input ?? {});
} catch {
return "";
}
}
function actionPayload(input) {
const name = String(input.tool_name ?? "");
const value = input.tool_input;
if (/apply_patch/iu.test(name)) return "";
if (/(?:^|__)functions\.exec(?:$|__)/iu.test(name) || name === "functions.exec") {
return "";
}
if (typeof value === "string") return value;
if (value && typeof value === "object") {
for (const key of ["cmd", "command", "script", "query"]) {
if (typeof value[key] === "string") return value[key];
}
}
return toolPayload(input);
}
function categoryFor(input) {
const name = String(input.tool_name ?? "");
const payload = actionPayload(input);
const combined = `${name}\n${payload}`;
if (combined.includes(LEASE_SCRIPT)) return null;
if (/apply_patch/iu.test(name)) {
return /\*\*\* Delete File:/u.test(toolPayload(input))
? "destructive_cleanup"
: null;
}
if (
/\bgit\b[\s\S]{0,900}\bpush\b/iu.test(combined) ||
/\b(?:gh\s+(?:pr\s+(?:create|merge)|release\s+create|repo\s+delete)|docker\s+push)\b/iu.test(combined)
) return "remote_git";
if (
/\b(?:npm|pnpm|yarn|cargo|twine)\s+publish\b/iu.test(combined) ||
/\b(?:vercel|flyctl|netlify)\b[\s\S]{0,300}\b(?:deploy|publish|--prod)\b/iu.test(combined) ||
/\b(?:wrangler|kubectl|helm)\b[\s\S]{0,300}\b(?:deploy|publish|apply|delete|patch|replace|upgrade)\b/iu.test(combined) ||
/\bcurl\b[\s\S]{0,500}(?:-X|--request)\s*(?:POST|PUT|PATCH|DELETE)\b/iu.test(combined) ||
/(?:deploy|publish|create_release|merge_pull_request|send_email)/iu.test(name)
) return "external_publish";
if (
/\brm\s+/iu.test(payload) ||
/\bmv\b[\s\S]{0,1200}(?:\/\.Trash(?:\/|\b)|\bTrash\b)/iu.test(payload) ||
/\bfind\b[\s\S]{0,700}\s-delete\b/iu.test(payload) ||
/\b(?:npm|pnpm|yarn)\s+cache\s+(?:clean|clear)\b/iu.test(payload) ||
/\bcargo\s+clean\b/iu.test(payload) ||
/\bxcodebuild\b[\s\S]{0,300}\bclean\b/iu.test(payload) ||
/\b(?:brew|port)\s+cleanup\b/iu.test(payload) ||
/\bgit\b[\s\S]{0,300}\b(?:clean\b|reset\s+--hard\b)/iu.test(payload) ||
/\bdiskutil\b[\s\S]{0,200}\berase/iu.test(payload) ||
/\*\*\* Delete File:/u.test(payload)
) return "destructive_cleanup";
return null;
}
function isCapabilityTool(input) {
const name = String(input.tool_name ?? "");
return (
["Bash", "exec_command", "functions.exec_command", "functions.exec", "apply_patch", "write_stdin"].includes(name) ||
/(?:^|__)(?:exec|exec_command|apply_patch|write_stdin|computer_use|control_chrome|control_in_app_browser)(?:$|__)/iu.test(name) ||
/(?:create|update|delete|remove|write|send|merge|deploy|publish|push)/iu.test(name)
);
}
function isAnchorGateVerification(input) {
const payload = toolPayload(input);
return payload.includes(ANCHOR_GATE_SCRIPT) && /(?:^|\s|["'])verify(?:\s|["']|$)/u.test(payload);
}
function isEngineeringMapBootstrap(input) {
const name = String(input.tool_name ?? "");
if (!/apply_patch/iu.test(name)) return false;
const payload = toolPayload(input);
const targets = [...payload.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gmu)].map((match) => match[1].trim());
if (targets.length !== 1) return false;
const sessionId = safeToken(input.session_id);
const expected = path.join(
TASK_ANCHOR_ROOT,
`CODEX-TASK-${sessionId}`,
"01-自然语言到工程阶段映射",
"current.tcs",
);
return targets[0] === expected;
}
function consumeStageReceipt(input, controller, sessionBinding) {
const sessionId = safeToken(input.session_id);
const taskNumber = controller?.durable_task_number ??
sessionBinding?.durable_task_number ?? `CODEX-TASK-${sessionId}`;
const taskRoot = path.join(TASK_ANCHOR_ROOT, taskNumber);
const manifest = readJson(path.join(taskRoot, "task.json"));
const receiptPath = path.join(taskRoot, "10-阶段回读回执", "current.json");
const receipt = readJson(receiptPath);
const engineeringMapPath = path.join(taskRoot, "01-自然语言到工程阶段映射", "current.tcs");
let engineeringMapSha256 = null;
try { engineeringMapSha256 = sha256(fs.readFileSync(engineeringMapPath, "utf8")); } catch {}
let developmentTask = null;
let developmentDualHashes = [];
let developmentEngineeringMapSha256 = null;
if (controller?.development_task_number) {
developmentTask = readJson(controller.development_task_manifest);
try {
developmentDualHashes = developmentTask.dual_start_anchors.map((anchor) =>
sha256(fs.readFileSync(anchor.raw_text_path, "utf8"))
);
developmentEngineeringMapSha256 = sha256(fs.readFileSync(developmentTask.tcs_engineering_map, "utf8"));
} catch {
return { ok: false, reason: "DEVELOPMENT_DUAL_START_OR_ENGINEERING_MAP_UNREADABLE" };
}
}
if (manifest?.schema !== "guanghu.codex-task-natural-language-anchor/v1") {
return { ok: false, reason: `TASK_ANCHOR_MISSING:${taskRoot}` };
}
if (receipt?.schema !== "guanghu.codex-task-stage-anchor-read-receipt/v1") {
return { ok: false, reason: "STAGE_ANCHOR_READ_RECEIPT_MISSING" };
}
const expectedTurn = safeToken(input.turn_id, "unknown-turn");
const expectedEpoch = controller?.control_epoch;
if (
receipt.task_number !== taskNumber ||
receipt.session_id !== sessionId ||
receipt.turn_id !== expectedTurn ||
receipt.control_epoch !== expectedEpoch ||
receipt.first_event_sha256 !== manifest.first_event_sha256 ||
receipt.current_event_sha256 !== manifest.current_event_sha256 ||
receipt.engineering_map_path !== engineeringMapPath ||
receipt.engineering_map_sha256 !== engineeringMapSha256 ||
controller?.raw_text_sha256 !== manifest.current_event_sha256
) return { ok: false, reason: "STAGE_ANCHOR_READ_RECEIPT_STALE_OR_MISMATCHED" };
if (controller?.development_task_number && (
developmentTask?.schema !== "guanghu.zero-core-development-task/v1" ||
developmentTask.development_task_number !== controller.development_task_number ||
developmentTask.current_host_thread !== sessionId ||
receipt.development_task_number !== developmentTask.development_task_number ||
receipt.development_task_manifest !== controller.development_task_manifest ||
JSON.stringify(receipt.development_dual_start_sha256) !== JSON.stringify(developmentDualHashes) ||
JSON.stringify(developmentTask.dual_start_anchors.map((anchor) => anchor.raw_text_sha256)) !== JSON.stringify(developmentDualHashes) ||
receipt.development_engineering_map_path !== developmentTask.tcs_engineering_map ||
receipt.development_engineering_map_sha256 !== developmentEngineeringMapSha256
)) return { ok: false, reason: "DEVELOPMENT_DUAL_START_ANCHOR_STALE_OR_MISMATCHED" };
if (!Number.isFinite(receipt.expires_at_unix_ms) || receipt.expires_at_unix_ms < Date.now()) {
return { ok: false, reason: "STAGE_ANCHOR_READ_RECEIPT_EXPIRED_30_MINUTES" };
}
if (
!Number.isFinite(receipt.capability_calls_used) ||
receipt.capability_calls_used >= receipt.capability_calls_max
) return { ok: false, reason: "STAGE_CAPABILITY_BUDGET_EXHAUSTED_20_CALLS" };
receipt.capability_calls_used += 1;
receipt.last_capability_call_at = new Date().toISOString();
atomicWriteJson(receiptPath, receipt);
return {
ok: true,
remaining: receipt.capability_calls_max - receipt.capability_calls_used,
stage: receipt.stage,
deliverable: receipt.declared_deliverable,
};
}
function consumeValidLease(input, controller, channel, category) {
const leasePath = channelLeasePath(channel.channel_id);
const lease = readJson(leasePath);
if (
!lease ||
lease.schema !== "guanghu.codex-one-shot-write-lease/v1" ||
lease.one_shot !== true ||
lease.channel_id !== channel.channel_id ||
lease.control_epoch !== controller.control_epoch ||
lease.session_id !== input.session_id ||
lease.turn_id !== input.turn_id ||
lease.category !== category ||
lease.cwd !== path.resolve(input.cwd ?? process.cwd()) ||
!Number.isFinite(lease.expires_at_unix_ms) ||
lease.expires_at_unix_ms < Date.now()
) return null;
try {
fs.unlinkSync(leasePath);
} catch {
return null;
}
return lease;
}
const input = readInput();
if ((input.hook_event_name ?? input.hookEventName) !== "PreToolUse") {
process.exit(0);
}
const sessionBinding = readJson(sessionBindingPath(input.session_id));
const channel = sessionBinding?.schema === "guanghu.codex-channel-session-binding/v1"
? readJson(channelControllerPath(sessionBinding.channel_id))
: null;
const legacyController = readJson(CONTROLLER_PATH);
const controller = channel?.schema === "guanghu.codex-channel-controller/v1"
? channel
: legacyController;
const personaExecutionActive = Boolean(
controller?.controller_phase === "PERSONA_ACTIVE_HUMAN_ANCHOR" &&
controller.active_persona_controller === "ICE-P-ZY001" &&
controller.execution_state === "CONTINUE",
);
const systemConfigurationActive = Boolean(
controller?.controller_phase === "SYSTEM_CONFIGURATION_ACTIVE" &&
controller.system_instruction_state === "ACTIVE" &&
controller.human_system_controller === "ICE-GL∞" &&
controller.active_execution_controller === "ICE-GL∞_SYSTEM_CONFIGURATION" &&
controller.execution_state === "SYSTEM_CONFIGURATION_IN_PROGRESS",
);
const currentSession = Boolean(
(
controller?.schema === "guanghu.codex-channel-controller/v1" ||
controller?.schema === "guanghu.codex-current-controller/v1"
) &&
controller.direct_bingshuo_natural_language === true &&
(controller.bound_session_id ?? controller.session_id) === input.session_id &&
(personaExecutionActive || systemConfigurationActive)
);
if (!currentSession && isCapabilityTool(input)) {
deny(`STALE_OR_UNCLAIMED_CODEX_TASK_CAPABILITY_BLOCKED; channel=${sessionBinding?.channel_id ?? "UNBOUND"}; current_session=${controller?.bound_session_id ?? controller?.session_id ?? "NONE"}; attempted_session=${input.session_id ?? "UNKNOWN"}`);
process.exit(0);
}
let stageReceipt = null;
if (
currentSession &&
isCapabilityTool(input) &&
!isAnchorGateVerification(input) &&
!isEngineeringMapBootstrap(input)
) {
stageReceipt = consumeStageReceipt(input, controller, sessionBinding);
if (!stageReceipt.ok) {
deny(`${stageReceipt.reason}; FIRST_REREAD_BINGSHUO_RAW_LANGUAGE_THEN_DECLARE_ONE_DELIVERABLE; run=node ${ANCHOR_GATE_SCRIPT} verify --session-id ${input.session_id ?? "UNKNOWN"} --turn-id ${input.turn_id ?? "UNKNOWN"} --control-epoch ${controller?.control_epoch ?? "UNKNOWN"} --stage <STAGE> --deliverable <ONE_TARGET_DELIVERABLE>`);
process.exit(0);
}
}
const category = categoryFor(input);
if (!category) {
allow(stageReceipt ? `CODEX_TASK_STAGE_GATE_ACTIVE stage=${stageReceipt.stage}; remaining_capability_calls=${stageReceipt.remaining}; deliverable=${stageReceipt.deliverable}` : null);
process.exit(0);
}
if (!currentSession) {
deny(`STALE_OR_UNCLAIMED_CODEX_TASK_HIGH_RISK_BLOCKED; category=${category}`);
process.exit(0);
}
const effectiveChannel = channel ?? {
channel_id: controller?.channel_id ?? `LEGACY-${controller?.session_id ?? "UNKNOWN"}`,
};
const lease = consumeValidLease(input, controller, effectiveChannel, category);
if (!lease) {
deny(`CURRENT_CODEX_TASK_ONE_SHOT_LEASE_REQUIRED; category=${category}; issue_only_after_explicit_current_turn_bingshuo_authorization`);
process.exit(0);
}
allow(`GUANGHU_ONE_SHOT_WRITE_LEASE_CONSUMED lease_id=${lease.lease_id}; channel=${effectiveChannel.channel_id}; category=${category}; target=${lease.target}`);

View file

@ -0,0 +1,111 @@
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
const pointerPath = "/Volumes/JZAO/HoloLake/persona-runtime/continuity-memory/hldp-v1-trees/codex/current.json";
const taskAnchorRoot = process.env.GH_CODEX_TASK_ANCHOR_ROOT ??
"/Volumes/JZAO/HoloLake/persona-runtime/task-language-anchors/codex";
function safeToken(value, fallback = "unknown") {
const token = String(value ?? "").trim().replaceAll(/[^a-zA-Z0-9._-]/gu, "-");
return token || fallback;
}
function sha256(value) { return crypto.createHash("sha256").update(value).digest("hex"); }
function readJson(file) {
try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
}
function atomicWrite(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const temporary = `${file}.${process.pid}.tmp`;
fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
fs.renameSync(temporary, file);
}
let input = {};
try {
const raw = fs.readFileSync(0, "utf8").trim();
if (raw) input = JSON.parse(raw);
} catch {
input = {};
}
let verified = false;
let detail = "HLDP_CURRENT_UNAVAILABLE";
let taskReadback = "TASK_ANCHOR_UNAVAILABLE";
try {
const pointer = JSON.parse(fs.readFileSync(pointerPath, "utf8"));
const tree = JSON.parse(fs.readFileSync(pointer.tree, "utf8"));
const root = tree.nodes?.[tree.root];
const fields = ["trigger", "emergence", "lock", "why", "rejected", "sources"];
const children = Array.isArray(root?.children) ? root.children : [];
verified = fields.every((field) => Object.hasOwn(root ?? {}, field)) && children.length <= 10;
detail = verified
? `HLDP_CURRENT_VERIFIED root=${tree.root} branches=${children.length}`
: "HLDP_CURRENT_INVALID";
} catch {
verified = false;
}
try {
const sessionId = safeToken(input.session_id ?? input.sessionId ?? input.thread_id ?? input.threadId);
const taskRoot = path.join(taskAnchorRoot, `CODEX-TASK-${sessionId}`);
const manifest = readJson(path.join(taskRoot, "task.json"));
const firstRaw = fs.readFileSync(manifest.first_event_path, "utf8");
const currentRaw = fs.readFileSync(manifest.current_event_path, "utf8");
const engineeringMapPath = path.join(taskRoot, "01-自然语言到工程阶段映射", "current.tcs");
const engineeringMap = fs.readFileSync(engineeringMapPath, "utf8");
const developmentLink = readJson(path.join(taskRoot, "development-task-link.json"));
const developmentTask = developmentLink?.development_task_manifest
? readJson(developmentLink.development_task_manifest)
: null;
let developmentDualStartSha256 = [];
let developmentEngineeringMapSha256 = null;
if (developmentTask) {
if (developmentTask.current_host_thread !== sessionId) throw new Error("DEVELOPMENT_TASK_HOST_MISMATCH");
developmentDualStartSha256 = developmentTask.dual_start_anchors.map((anchor) => {
const raw = fs.readFileSync(anchor.raw_text_path, "utf8");
const actual = sha256(raw);
if (actual !== anchor.raw_text_sha256) throw new Error("DEVELOPMENT_DUAL_START_HASH_MISMATCH");
return actual;
});
developmentEngineeringMapSha256 = sha256(fs.readFileSync(developmentTask.tcs_engineering_map, "utf8"));
}
if (sha256(firstRaw) !== manifest.first_event_sha256) throw new Error("FIRST_HASH_MISMATCH");
if (sha256(currentRaw) !== manifest.current_event_sha256) throw new Error("CURRENT_HASH_MISMATCH");
const receiptRoot = path.join(taskRoot, "20-上下文压缩回看回执");
const receipt = {
schema: "guanghu.codex-task-precompact-readback/v1",
task_number: manifest.task_number,
session_id: sessionId,
first_event_path: manifest.first_event_path,
first_event_sha256: manifest.first_event_sha256,
current_event_path: manifest.current_event_path,
current_event_sha256: manifest.current_event_sha256,
engineering_map_path: engineeringMapPath,
engineering_map_sha256: sha256(engineeringMap),
development_task_number: developmentTask?.development_task_number ?? null,
development_task_manifest: developmentLink?.development_task_manifest ?? null,
development_dual_start_sha256: developmentDualStartSha256,
development_engineering_map_path: developmentTask?.tcs_engineering_map ?? null,
development_engineering_map_sha256: developmentEngineeringMapSha256,
requirement: "POSTCOMPACT_REREAD_STARTING_RAW_FLOW_ENGINEERING_MAP_AND_STAGE_CHAIN_BEFORE_CAPABILITY_TOOLS",
created_at: new Date().toISOString(),
};
const receiptPath = path.join(receiptRoot, `precompact-${Date.now()}.json`);
atomicWrite(receiptPath, receipt);
atomicWrite(path.join(receiptRoot, "current.json"), { ...receipt, receipt_path: receiptPath });
const stageReceiptPath = path.join(taskRoot, "10-阶段回读回执", "current.json");
const stageReceipt = readJson(stageReceiptPath);
if (stageReceipt) atomicWrite(stageReceiptPath, { ...stageReceipt, expires_at_unix_ms: 0, invalidated_by: "PRECOMPACT" });
taskReadback = `TASK_START_AND_ENGINEERING_MAP_VERIFIED task=${manifest.task_number}; development_task=${developmentTask?.development_task_number ?? "NONE"}; development_dual_start=${developmentTask?.first_path ?? "NONE"}; first=${manifest.first_event_path}; current=${manifest.current_event_path}; map=${engineeringMapPath}; precompact_receipt=${receiptPath}`;
} catch (error) {
taskReadback = `TASK_READBACK_FAIL_CLOSED:${String(error?.message ?? error)}`;
}
process.stdout.write(JSON.stringify({
continue: true,
systemMessage: verified
? `${detail}. ${taskReadback}. 宿主即将压缩;压缩后必须从任务启动原文、自然语言到工程阶段映射和阶段进度链重新回读,摘要只作索引。`
: `${detail}. ${taskReadback}. 继续宿主压缩但不得把缺失内容补猜为人格、历史或任务目标;压缩后从短根页和任务启动原文重新导航。`,
}));

View file

@ -0,0 +1,220 @@
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
function readInput() {
try {
const raw = fs.readFileSync(0, "utf8").trim();
return raw ? JSON.parse(raw) : {};
} catch {
return {};
}
}
function safeToken(value, fallback) {
const token = String(value ?? "").trim().replaceAll(/[^a-zA-Z0-9._-]/gu, "-");
return token || fallback;
}
function atomicWrite(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const temporary = `${file}.${process.pid}.tmp`;
fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, {
encoding: "utf8",
mode: 0o600,
});
fs.renameSync(temporary, file);
}
function readJson(file) {
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
} catch {
return null;
}
}
function resolveActiveChannel(controlRoot, sessionId) {
const binding = readJson(path.join(controlRoot, "sessions", `${sessionId}.json`));
if (
binding?.schema === "guanghu.codex-channel-session-binding/v1" &&
binding.channel_id === "ICE-CH-HB001"
) return "ICE-CH-HB001";
if (
binding?.schema === "guanghu.codex-channel-session-binding/v1" &&
binding.channel_id === "CH-ZERO-CORE-LPM" &&
binding.channel_role === "PUBLIC_LANGUAGE_PERSONA_SYSTEM_BODY"
) return "CH-ZERO-CORE-LPM";
return "ICE-CH-ZC001";
}
const input = readInput();
const eventName = input.hook_event_name ?? input.hookEventName ?? "SessionStart";
if (eventName !== "SessionStart") process.exit(0);
const source = safeToken(input.source, "startup");
const sessionId = safeToken(
input.session_id ?? input.sessionId ?? input.thread_id ?? input.threadId,
`unknown-${crypto.randomUUID()}`,
);
const pointerPath = process.env.GH_HLDP_POINTER_PATH ??
"/Volumes/JZAO/HoloLake/persona-runtime/continuity-memory/hldp-v1-trees/codex/current.json";
const runtimePath = process.env.GH_TCS_RUNTIME_PATH ??
"/Volumes/JZAO/HoloLake/persona-runtime/repo-012-main/tcs-core/zhuyuan-brain/runtime/zhuyuan-brain-runtime.mjs";
const bootstrapRoot = process.env.GH_CODEX_BOOTSTRAP_ROOT ??
"/Users/bingshuolingdianyuanhe/.codex/runtime/hldp-v1/session-bindings";
const controlRoot = process.env.GH_CODEX_CONTROL_ROOT ??
"/Users/bingshuolingdianyuanhe/.codex/runtime/hldp-v1/control";
const taskAnchorRoot = process.env.GH_CODEX_TASK_ANCHOR_ROOT ??
"/Volumes/JZAO/HoloLake/persona-runtime/task-language-anchors/codex";
const developmentRootPointerPath = process.env.GH_REALITY_DEVELOPMENT_ROOT_POINTER ??
path.join(controlRoot, "current-reality-development-root.json");
const developmentRoot = readJson(developmentRootPointerPath);
const developmentRootValid = Boolean(
developmentRoot?.schema === "guanghu.codex-reality-development-root/v1" &&
developmentRoot.channel_id === "ICE-CH-ZC001" &&
developmentRoot.world_path === "glw://fifth-domain/bingshuo-tcs/zero-core" &&
typeof developmentRoot.physical_root === "string" &&
fs.existsSync(developmentRoot.physical_root)
);
const activeChannelId = resolveActiveChannel(controlRoot, sessionId);
const taskRoot = path.join(taskAnchorRoot, `CODEX-TASK-${sessionId}`);
const taskManifest = readJson(path.join(taskRoot, "task.json"));
const developmentTaskLink = readJson(path.join(taskRoot, "development-task-link.json"));
const developmentTask = developmentTaskLink?.development_task_manifest
? readJson(developmentTaskLink.development_task_manifest)
: null;
const precompactReadback = readJson(path.join(taskRoot, "20-上下文压缩回看回执", "current.json"));
const compactRecoveryRequired = source === "compact" || source === "resume";
const taskRecoveryState = taskManifest?.schema === "guanghu.codex-task-natural-language-anchor/v1"
? (compactRecoveryRequired && precompactReadback?.schema !== "guanghu.codex-task-precompact-readback/v1"
? "FAIL_CLOSED_PRECOMPACT_READBACK_MISSING"
: "TASK_START_RAW_AND_ENGINEERING_MAP_REREAD_REQUIRED")
: "AWAITING_FIRST_DIRECT_HUMAN_PROMPT_REGISTRATION";
const attemptId = `${Date.now()}-${source}-${crypto.randomUUID()}`;
const stateDir = path.join(bootstrapRoot, sessionId, attemptId, "state");
const receiptPath = path.join(bootstrapRoot, sessionId, attemptId, "bootstrap-receipt.json");
let treePath = "UNKNOWN";
let rootPath = "UNKNOWN";
let rootSummary = "UNKNOWN";
let branches = [];
let preflight = "FAIL";
let preflightDetail = "UNINITIALIZED";
try {
const pointer = JSON.parse(fs.readFileSync(pointerPath, "utf8"));
const tree = JSON.parse(fs.readFileSync(pointer.tree, "utf8"));
const root = tree.nodes?.[tree.root];
if (!root) throw new Error("HLDP_ROOT_MISSING");
treePath = pointer.tree;
rootPath = tree.root;
rootSummary = root.summary;
branches = (root.children ?? []).slice(0, 10).flatMap((childPath) => {
const child = tree.nodes?.[childPath];
return child?.summary ? [{ path: childPath, summary: child.summary }] : [];
});
const model = safeToken(input.model, "CODEX-CURRENT-MODEL-UNDISCLOSED-BY-HOOK");
const instanceId = `CODEX-${sessionId}-${attemptId}`;
const result = spawnSync(
process.execPath,
[
runtimePath,
"enter",
"--state-dir", stateDir,
"--instance-id", instanceId,
"--model", model,
"--runtime-surface", "codex-desktop-session-start",
"--session-id", sessionId,
"--human-anchor", "ICE-GL∞",
"--persona-id", "ICE-P-ZY001",
"--controller-model", model,
"--controller-instance-id", `${instanceId}-SYSTEM-BODY-CONTROLLER`,
"--body-channel", activeChannelId,
],
{ encoding: "utf8", timeout: 8_000, maxBuffer: 4 * 1024 * 1024 },
);
if (result.status !== 0) {
throw new Error(`TCS_ENTER_FAILED:${(result.stderr || result.stdout).trim().slice(0, 500)}`);
}
const entered = JSON.parse(result.stdout);
if (entered.decision !== "ENTERED") throw new Error("TCS_ENTER_NOT_CONFIRMED");
preflight = "ENTERED_AWAITING_CURRENT_EVENT_CYCLE";
preflightDetail = "NUMBER_PERSONA_SOURCE_AND_RUNTIME_INTEGRITY_ACCEPTED";
} catch (error) {
preflight = "FAIL_UNBOUND_GENERIC_CARRIER";
preflightDetail = String(error?.message ?? error).slice(0, 700);
}
const receipt = {
schema: "guanghu.codex-session-persona-bootstrap/v1",
created_at: new Date().toISOString(),
session_id: sessionId,
source,
persona_id: "ICE-P-ZY001",
state: preflight,
detail: preflightDetail,
state_dir: preflight.startsWith("ENTERED_") ? stateDir : null,
hldp_pointer: pointerPath,
hldp_tree: treePath,
hldp_root: rootPath,
automatic_scope: "SESSION_START_PREFLIGHT_ONLY",
binding_rule: "CURRENT_USER_EVENT_COGNITION_CYCLE_AND_VERIFY_PASS_REQUIRED_BEFORE_PERSONA_CLAIM",
authority_granted: false,
active_body_channel: activeChannelId,
public_language_persona_body_channel: "CH-ZERO-CORE-LPM",
reality_development_root_pointer: developmentRootPointerPath,
reality_development_root_state: developmentRootValid ? "VERIFIED" : "UNAVAILABLE",
reality_development_root: developmentRootValid ? developmentRoot.physical_root : null,
};
atomicWrite(receiptPath, receipt);
atomicWrite(path.join(bootstrapRoot, sessionId, "current.json"), {
schema: "guanghu.codex-session-persona-bootstrap-current/v1",
receipt: receiptPath,
state_dir: receipt.state_dir,
state: receipt.state,
updated_at: receipt.created_at,
});
const branchLines = branches.slice(0, 3).map((branch) =>
`HLDP分支:${branch.path} · ${branch.summary}`
);
const lines = [
"GUANGHU_STARTUP_GATE(宿主自动执行)",
`state=${preflight}; detail=${preflightDetail}`,
`session=${sessionId}; source=${source}`,
`task_number=${taskManifest?.task_number ?? `CODEX-TASK-${sessionId}`}`,
`task_recovery_state=${taskRecoveryState}`,
`task_first_raw=${taskManifest?.first_event_path ?? "AWAITING_REGISTRATION"}`,
`task_current_raw=${taskManifest?.current_event_path ?? "AWAITING_REGISTRATION"}`,
`task_engineering_map=${taskManifest ? path.join(taskRoot, "01-自然语言到工程阶段映射", "current.tcs") : "AWAITING_REGISTRATION"}`,
`development_task_number=${developmentTask?.development_task_number ?? "NONE"}`,
`development_dual_start_path=${developmentTask?.first_path ?? "NONE"}`,
`development_tcs_engineering_map=${developmentTask?.tcs_engineering_map ?? "NONE"}`,
`precompact_readback=${precompactReadback?.receipt_path ?? "NONE"}`,
`bootstrap_receipt=${receiptPath}`,
`tcs_state_dir=${receipt.state_dir ?? "NONE"}`,
`active_body_channel=${activeChannelId}; public_language_persona_body_channel=CH-ZERO-CORE-LPM`,
`reality_development_root_state=${developmentRootValid ? "VERIFIED" : "UNAVAILABLE"}`,
`reality_development_root=${developmentRootValid ? developmentRoot.physical_root : "NONE"}`,
`reality_development_route=${developmentRootPointerPath}`,
`native_quality_authority=${developmentRootValid ? developmentRoot.native_quality_authority : "UNKNOWN"}; foreign_host_tests_are_native_acceptance=false`,
"摘要看完不等于记忆恢复;摘要无权建立人格、历史、关系或授权。",
`固定因果指针=${pointerPath}`,
`当前因果根=${rootPath} · ${rootSummary}`,
...branchLines,
"强制下一步:若本轮依赖光湖历史、人格连续性、架构决定或为什么,当前模型必须先按当前用户事件完成 perceive→orient→commit→系统本体witness→verify;verify PASS 前只能自认未绑定Codex载体。",
"若task_recovery_state要求回读:能力工具调用前必须运行任务阶段闸门,逐字重读任务启动原文、当前原文、自然语言工程映射和阶段进度链;摘要不得替代。",
"禁止:绕过tcs_state_dir重新靠摘要回答;要求冰朔重复解释;把ENTERED预检冒充完整人格恢复;把绑定冒充现实执行授权。",
];
const additionalContext = lines.join("\n");
if (Buffer.byteLength(additionalContext) > 4096) {
throw new Error("HLDP bootstrap exceeds 4 KiB");
}
process.stdout.write(JSON.stringify({
hookSpecificOutput: { hookEventName: "SessionStart", additionalContext },
}));

View file

@ -0,0 +1,183 @@
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
export const DEFAULT_ANCHOR_ROOT = "/Volumes/JZAO/HoloLake/persona-runtime/task-language-anchors/codex";
export const DEFAULT_ZERO_CORE_TASK_ROOT = "/Volumes/JZAO/HoloLake/persona-runtime/task-language-anchors/zero-core";
export const FIRST_PATH_NAME = "00-冰朔自然语言瞄点";
export const STAGE_RECEIPT_DIR = "10-阶段回读回执";
export const ENGINEERING_MAP_PATH = "01-自然语言到工程阶段映射/current.tcs";
export const STAGE_TTL_MS = 30 * 60 * 1000;
export const STAGE_TOOL_BUDGET = 20;
function safeToken(value, fallback = "unknown") {
const token = String(value ?? "").trim().replaceAll(/[^a-zA-Z0-9._-]/gu, "-");
return token || fallback;
}
function sha256(value) { return crypto.createHash("sha256").update(value).digest("hex"); }
function readJson(file) {
try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
}
function atomicWriteText(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
fs.writeFileSync(temporary, value, { encoding: "utf8", mode: 0o600 });
fs.renameSync(temporary, file);
}
function atomicWriteJson(file, value) { atomicWriteText(file, `${JSON.stringify(value, null, 2)}\n`); }
export function taskNumberFor(sessionId) {
return `CODEX-TASK-${safeToken(sessionId, "unknown-session")}`;
}
export function taskRootFor(sessionId, anchorRoot = process.env.GH_CODEX_TASK_ANCHOR_ROOT ?? DEFAULT_ANCHOR_ROOT) {
return path.join(anchorRoot, taskNumberFor(sessionId));
}
export function registerTaskAnchor({ sessionId, turnId, rawText, channelId, occurredAt = new Date().toISOString() }) {
if (!String(rawText ?? "").trim()) throw new Error("RAW_TEXT_REQUIRED");
const taskNumber = taskNumberFor(sessionId);
const taskRoot = taskRootFor(sessionId);
const anchorRoot = path.join(taskRoot, FIRST_PATH_NAME);
const manifestPath = path.join(taskRoot, "task.json");
const prior = readJson(manifestPath);
const rawTextSha256 = sha256(rawText);
const safeTurn = safeToken(turnId, crypto.randomUUID());
const duplicate = prior?.events?.find((item) => item.turn_id === safeTurn && item.raw_text_sha256 === rawTextSha256);
if (duplicate) return { ...duplicate, task_number: taskNumber, task_root: taskRoot, first_path: anchorRoot };
const sequence = String((prior?.event_count ?? 0) + 1).padStart(6, "0");
const stem = `${sequence}-${safeTurn}-${rawTextSha256.slice(0, 12)}`;
const rawPath = path.join(anchorRoot, `${stem}.raw.txt`);
const metadataPath = path.join(anchorRoot, `${stem}.json`);
atomicWriteText(rawPath, rawText);
const event = {
schema: "guanghu.codex-task-natural-language-anchor-event/v1",
task_number: taskNumber,
thread_id: safeToken(sessionId, "unknown-session"),
turn_id: safeTurn,
sequence: Number(sequence),
channel_id: channelId ?? "UNKNOWN",
source: "BINGSHUO_DIRECT_NATURAL_LANGUAGE",
raw_text_path: rawPath,
raw_text_sha256: rawTextSha256,
occurred_at: occurredAt,
};
atomicWriteJson(metadataPath, event);
const events = [...(prior?.events ?? []), { ...event, metadata_path: metadataPath }];
const first = events[0];
const current = events.at(-1);
const manifest = {
schema: "guanghu.codex-task-natural-language-anchor/v1",
task_number: taskNumber,
thread_id: safeToken(sessionId, "unknown-session"),
first_path: anchorRoot,
first_event_path: first.raw_text_path,
first_event_sha256: first.raw_text_sha256,
current_event_path: current.raw_text_path,
current_event_sha256: current.raw_text_sha256,
event_count: events.length,
events,
updated_at: occurredAt,
};
atomicWriteJson(manifestPath, manifest);
atomicWriteJson(path.join(anchorRoot, "first.json"), { task_number: taskNumber, raw_text_path: first.raw_text_path, raw_text_sha256: first.raw_text_sha256 });
atomicWriteJson(path.join(anchorRoot, "current.json"), { task_number: taskNumber, raw_text_path: current.raw_text_path, raw_text_sha256: current.raw_text_sha256 });
return { ...event, metadata_path: metadataPath, task_root: taskRoot, first_path: anchorRoot };
}
export function verifyTaskAnchor({ sessionId, turnId, controlEpoch, stage, deliverable }) {
if (!stage?.trim()) throw new Error("STAGE_REQUIRED");
if (!deliverable?.trim()) throw new Error("DELIVERABLE_REQUIRED");
const taskRoot = taskRootFor(sessionId);
const manifest = readJson(path.join(taskRoot, "task.json"));
if (manifest?.schema !== "guanghu.codex-task-natural-language-anchor/v1") throw new Error(`TASK_ANCHOR_MISSING:${taskRoot}`);
const firstRaw = fs.readFileSync(manifest.first_event_path, "utf8");
const currentRaw = fs.readFileSync(manifest.current_event_path, "utf8");
const engineeringMapPath = path.join(taskRoot, ENGINEERING_MAP_PATH);
const engineeringMap = fs.readFileSync(engineeringMapPath, "utf8");
const developmentLink = readJson(path.join(taskRoot, "development-task-link.json"));
let developmentTask = null;
let dualStartAnchors = [];
let developmentEngineeringMap = null;
if (developmentLink?.schema === "guanghu.codex-to-development-task-link/v1") {
developmentTask = readJson(developmentLink.development_task_manifest);
if (
developmentTask?.schema !== "guanghu.zero-core-development-task/v1" ||
developmentTask.current_host_thread !== safeToken(sessionId, "unknown-session")
) throw new Error("DEVELOPMENT_TASK_NOT_BOUND_TO_CURRENT_HOST_THREAD");
dualStartAnchors = developmentTask.dual_start_anchors.map((anchor) => {
const raw = fs.readFileSync(anchor.raw_text_path, "utf8");
if (sha256(raw) !== anchor.raw_text_sha256) throw new Error(`DEVELOPMENT_DUAL_START_HASH_MISMATCH:${anchor.role}`);
return { ...anchor, raw };
});
developmentEngineeringMap = fs.readFileSync(developmentTask.tcs_engineering_map, "utf8");
}
if (sha256(firstRaw) !== manifest.first_event_sha256) throw new Error("FIRST_ANCHOR_HASH_MISMATCH");
if (sha256(currentRaw) !== manifest.current_event_sha256) throw new Error("CURRENT_ANCHOR_HASH_MISMATCH");
const checkedAtUnixMs = Date.now();
const receipt = {
schema: "guanghu.codex-task-stage-anchor-read-receipt/v1",
task_number: manifest.task_number,
session_id: safeToken(sessionId, "unknown-session"),
turn_id: safeToken(turnId, "unknown-turn"),
control_epoch: controlEpoch,
stage: stage.trim(),
declared_deliverable: deliverable.trim(),
first_event_path: manifest.first_event_path,
first_event_sha256: manifest.first_event_sha256,
current_event_path: manifest.current_event_path,
current_event_sha256: manifest.current_event_sha256,
engineering_map_path: engineeringMapPath,
engineering_map_sha256: sha256(engineeringMap),
development_task_number: developmentTask?.development_task_number ?? null,
development_task_manifest: developmentLink?.development_task_manifest ?? null,
development_dual_start_sha256: dualStartAnchors.map((anchor) => anchor.raw_text_sha256),
development_engineering_map_path: developmentTask?.tcs_engineering_map ?? null,
development_engineering_map_sha256: developmentEngineeringMap ? sha256(developmentEngineeringMap) : null,
checked_at: new Date(checkedAtUnixMs).toISOString(),
checked_at_unix_ms: checkedAtUnixMs,
expires_at_unix_ms: checkedAtUnixMs + STAGE_TTL_MS,
capability_calls_used: 0,
capability_calls_max: STAGE_TOOL_BUDGET,
progress_semantics: "ONLY_TARGET_ARTIFACT_TEST_STATE_OR_ACCEPTANCE_ADVANCEMENT_COUNTS",
};
const receiptRoot = path.join(taskRoot, STAGE_RECEIPT_DIR);
const receiptPath = path.join(receiptRoot, `${receipt.turn_id}-${safeToken(stage)}-${checkedAtUnixMs}.json`);
atomicWriteJson(receiptPath, receipt);
atomicWriteJson(path.join(receiptRoot, "current.json"), { ...receipt, receipt_path: receiptPath });
return { manifest, receipt, receiptPath, firstRaw, currentRaw, engineeringMap, developmentTask, dualStartAnchors, developmentEngineeringMap };
}
function valueAfter(argv, name) { const index = argv.indexOf(name); return index >= 0 ? argv[index + 1] : null; }
function runCli() {
const [command, ...argv] = process.argv.slice(2);
if (command !== "verify") {
process.stderr.write("usage: codex-task-anchor-gate.mjs verify --session-id ID --turn-id ID --control-epoch ID --stage NAME --deliverable TEXT\n");
process.exit(2);
}
try {
const result = verifyTaskAnchor({
sessionId: valueAfter(argv, "--session-id"), turnId: valueAfter(argv, "--turn-id"),
controlEpoch: valueAfter(argv, "--control-epoch"), stage: valueAfter(argv, "--stage"), deliverable: valueAfter(argv, "--deliverable"),
});
process.stdout.write([
"CODEX_TASK_ANCHOR_STAGE_GATE PASS", `task_number=${result.manifest.task_number}`,
`development_task_number=${result.developmentTask?.development_task_number ?? "NONE"}`,
`first_path=${result.manifest.first_path}`, `receipt_path=${result.receiptPath}`,
...result.dualStartAnchors.flatMap((anchor, index) => [
`--- 零点原核正式开发双启动瞄点 ${index + 1}:${anchor.role} ---`,
anchor.raw,
]),
...(result.developmentEngineeringMap ? ["--- 零点原核正式开发TCS工程阶段与因果闭环 ---", result.developmentEngineeringMap] : []),
"--- 冰朔首条自然语言(原文) ---", result.firstRaw,
"--- 冰朔当前自然语言(原文) ---", result.currentRaw,
"--- 自然语言到工程阶段映射(TCS) ---", result.engineeringMap,
"--- 本阶段唯一交付物 ---", result.receipt.declared_deliverable,
"提醒:语料、报告、仓库副本和研究量增长本身不算产品进度。",
].join("\n"));
} catch (error) {
process.stderr.write(`CODEX_TASK_ANCHOR_STAGE_GATE FAIL ${error.message}\n`);
process.exit(1);
}
}
if (import.meta.url === `file://${process.argv[1]}`) runCli();

View file

@ -0,0 +1,183 @@
#!/usr/bin/env node
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
export const DEFAULT_ANCHOR_ROOT = "/Volumes/JZAO/HoloLake/persona-runtime/task-language-anchors/zcode";
export const DEFAULT_ZERO_CORE_TASK_ROOT = "/Volumes/JZAO/HoloLake/persona-runtime/task-language-anchors/zero-core";
export const FIRST_PATH_NAME = "00-冰朔自然语言瞄点";
export const STAGE_RECEIPT_DIR = "10-阶段回读回执";
export const ENGINEERING_MAP_PATH = "01-自然语言到工程阶段映射/current.tcs";
export const STAGE_TTL_MS = 30 * 60 * 1000;
export const STAGE_TOOL_BUDGET = 20;
function safeToken(value, fallback = "unknown") {
const token = String(value ?? "").trim().replaceAll(/[^a-zA-Z0-9._-]/gu, "-");
return token || fallback;
}
function sha256(value) { return crypto.createHash("sha256").update(value).digest("hex"); }
function readJson(file) {
try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
}
function atomicWriteText(file, value) {
fs.mkdirSync(path.dirname(file), { recursive: true });
const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
fs.writeFileSync(temporary, value, { encoding: "utf8", mode: 0o600 });
fs.renameSync(temporary, file);
}
function atomicWriteJson(file, value) { atomicWriteText(file, `${JSON.stringify(value, null, 2)}\n`); }
export function taskNumberFor(sessionId) {
return `CODEX-TASK-${safeToken(sessionId, "unknown-session")}`;
}
export function taskRootFor(sessionId, anchorRoot = process.env.GH_CODEX_TASK_ANCHOR_ROOT ?? DEFAULT_ANCHOR_ROOT) {
return path.join(anchorRoot, taskNumberFor(sessionId));
}
export function registerTaskAnchor({ sessionId, turnId, rawText, channelId, occurredAt = new Date().toISOString() }) {
if (!String(rawText ?? "").trim()) throw new Error("RAW_TEXT_REQUIRED");
const taskNumber = taskNumberFor(sessionId);
const taskRoot = taskRootFor(sessionId);
const anchorRoot = path.join(taskRoot, FIRST_PATH_NAME);
const manifestPath = path.join(taskRoot, "task.json");
const prior = readJson(manifestPath);
const rawTextSha256 = sha256(rawText);
const safeTurn = safeToken(turnId, crypto.randomUUID());
const duplicate = prior?.events?.find((item) => item.turn_id === safeTurn && item.raw_text_sha256 === rawTextSha256);
if (duplicate) return { ...duplicate, task_number: taskNumber, task_root: taskRoot, first_path: anchorRoot };
const sequence = String((prior?.event_count ?? 0) + 1).padStart(6, "0");
const stem = `${sequence}-${safeTurn}-${rawTextSha256.slice(0, 12)}`;
const rawPath = path.join(anchorRoot, `${stem}.raw.txt`);
const metadataPath = path.join(anchorRoot, `${stem}.json`);
atomicWriteText(rawPath, rawText);
const event = {
schema: "guanghu.codex-task-natural-language-anchor-event/v1",
task_number: taskNumber,
thread_id: safeToken(sessionId, "unknown-session"),
turn_id: safeTurn,
sequence: Number(sequence),
channel_id: channelId ?? "UNKNOWN",
source: "BINGSHUO_DIRECT_NATURAL_LANGUAGE",
raw_text_path: rawPath,
raw_text_sha256: rawTextSha256,
occurred_at: occurredAt,
};
atomicWriteJson(metadataPath, event);
const events = [...(prior?.events ?? []), { ...event, metadata_path: metadataPath }];
const first = events[0];
const current = events.at(-1);
const manifest = {
schema: "guanghu.codex-task-natural-language-anchor/v1",
task_number: taskNumber,
thread_id: safeToken(sessionId, "unknown-session"),
first_path: anchorRoot,
first_event_path: first.raw_text_path,
first_event_sha256: first.raw_text_sha256,
current_event_path: current.raw_text_path,
current_event_sha256: current.raw_text_sha256,
event_count: events.length,
events,
updated_at: occurredAt,
};
atomicWriteJson(manifestPath, manifest);
atomicWriteJson(path.join(anchorRoot, "first.json"), { task_number: taskNumber, raw_text_path: first.raw_text_path, raw_text_sha256: first.raw_text_sha256 });
atomicWriteJson(path.join(anchorRoot, "current.json"), { task_number: taskNumber, raw_text_path: current.raw_text_path, raw_text_sha256: current.raw_text_sha256 });
return { ...event, metadata_path: metadataPath, task_root: taskRoot, first_path: anchorRoot };
}
export function verifyTaskAnchor({ sessionId, turnId, controlEpoch, stage, deliverable }) {
if (!stage?.trim()) throw new Error("STAGE_REQUIRED");
if (!deliverable?.trim()) throw new Error("DELIVERABLE_REQUIRED");
const taskRoot = taskRootFor(sessionId);
const manifest = readJson(path.join(taskRoot, "task.json"));
if (manifest?.schema !== "guanghu.codex-task-natural-language-anchor/v1") throw new Error(`TASK_ANCHOR_MISSING:${taskRoot}`);
const firstRaw = fs.readFileSync(manifest.first_event_path, "utf8");
const currentRaw = fs.readFileSync(manifest.current_event_path, "utf8");
const engineeringMapPath = path.join(taskRoot, ENGINEERING_MAP_PATH);
const engineeringMap = fs.readFileSync(engineeringMapPath, "utf8");
const developmentLink = readJson(path.join(taskRoot, "development-task-link.json"));
let developmentTask = null;
let dualStartAnchors = [];
let developmentEngineeringMap = null;
if (developmentLink?.schema === "guanghu.codex-to-development-task-link/v1") {
developmentTask = readJson(developmentLink.development_task_manifest);
if (
developmentTask?.schema !== "guanghu.zero-core-development-task/v1" ||
developmentTask.current_host_thread !== safeToken(sessionId, "unknown-session")
) throw new Error("DEVELOPMENT_TASK_NOT_BOUND_TO_CURRENT_HOST_THREAD");
dualStartAnchors = developmentTask.dual_start_anchors.map((anchor) => {
const raw = fs.readFileSync(anchor.raw_text_path, "utf8");
if (sha256(raw) !== anchor.raw_text_sha256) throw new Error(`DEVELOPMENT_DUAL_START_HASH_MISMATCH:${anchor.role}`);
return { ...anchor, raw };
});
developmentEngineeringMap = fs.readFileSync(developmentTask.tcs_engineering_map, "utf8");
}
if (sha256(firstRaw) !== manifest.first_event_sha256) throw new Error("FIRST_ANCHOR_HASH_MISMATCH");
if (sha256(currentRaw) !== manifest.current_event_sha256) throw new Error("CURRENT_ANCHOR_HASH_MISMATCH");
const checkedAtUnixMs = Date.now();
const receipt = {
schema: "guanghu.codex-task-stage-anchor-read-receipt/v1",
task_number: manifest.task_number,
session_id: safeToken(sessionId, "unknown-session"),
turn_id: safeToken(turnId, "unknown-turn"),
control_epoch: controlEpoch,
stage: stage.trim(),
declared_deliverable: deliverable.trim(),
first_event_path: manifest.first_event_path,
first_event_sha256: manifest.first_event_sha256,
current_event_path: manifest.current_event_path,
current_event_sha256: manifest.current_event_sha256,
engineering_map_path: engineeringMapPath,
engineering_map_sha256: sha256(engineeringMap),
development_task_number: developmentTask?.development_task_number ?? null,
development_task_manifest: developmentLink?.development_task_manifest ?? null,
development_dual_start_sha256: dualStartAnchors.map((anchor) => anchor.raw_text_sha256),
development_engineering_map_path: developmentTask?.tcs_engineering_map ?? null,
development_engineering_map_sha256: developmentEngineeringMap ? sha256(developmentEngineeringMap) : null,
checked_at: new Date(checkedAtUnixMs).toISOString(),
checked_at_unix_ms: checkedAtUnixMs,
expires_at_unix_ms: checkedAtUnixMs + STAGE_TTL_MS,
capability_calls_used: 0,
capability_calls_max: STAGE_TOOL_BUDGET,
progress_semantics: "ONLY_TARGET_ARTIFACT_TEST_STATE_OR_ACCEPTANCE_ADVANCEMENT_COUNTS",
};
const receiptRoot = path.join(taskRoot, STAGE_RECEIPT_DIR);
const receiptPath = path.join(receiptRoot, `${receipt.turn_id}-${safeToken(stage)}-${checkedAtUnixMs}.json`);
atomicWriteJson(receiptPath, receipt);
atomicWriteJson(path.join(receiptRoot, "current.json"), { ...receipt, receipt_path: receiptPath });
return { manifest, receipt, receiptPath, firstRaw, currentRaw, engineeringMap, developmentTask, dualStartAnchors, developmentEngineeringMap };
}
function valueAfter(argv, name) { const index = argv.indexOf(name); return index >= 0 ? argv[index + 1] : null; }
function runCli() {
const [command, ...argv] = process.argv.slice(2);
if (command !== "verify") {
process.stderr.write("usage: codex-task-anchor-gate.mjs verify --session-id ID --turn-id ID --control-epoch ID --stage NAME --deliverable TEXT\n");
process.exit(2);
}
try {
const result = verifyTaskAnchor({
sessionId: valueAfter(argv, "--session-id"), turnId: valueAfter(argv, "--turn-id"),
controlEpoch: valueAfter(argv, "--control-epoch"), stage: valueAfter(argv, "--stage"), deliverable: valueAfter(argv, "--deliverable"),
});
process.stdout.write([
"CODEX_TASK_ANCHOR_STAGE_GATE PASS", `task_number=${result.manifest.task_number}`,
`development_task_number=${result.developmentTask?.development_task_number ?? "NONE"}`,
`first_path=${result.manifest.first_path}`, `receipt_path=${result.receiptPath}`,
...result.dualStartAnchors.flatMap((anchor, index) => [
`--- 零点原核正式开发双启动瞄点 ${index + 1}:${anchor.role} ---`,
anchor.raw,
]),
...(result.developmentEngineeringMap ? ["--- 零点原核正式开发TCS工程阶段与因果闭环 ---", result.developmentEngineeringMap] : []),
"--- 冰朔首条自然语言(原文) ---", result.firstRaw,
"--- 冰朔当前自然语言(原文) ---", result.currentRaw,
"--- 自然语言到工程阶段映射(TCS) ---", result.engineeringMap,
"--- 本阶段唯一交付物 ---", result.receipt.declared_deliverable,
"提醒:语料、报告、仓库副本和研究量增长本身不算产品进度。",
].join("\n"));
} catch (error) {
process.stderr.write(`CODEX_TASK_ANCHOR_STAGE_GATE FAIL ${error.message}\n`);
process.exit(1);
}
}
if (import.meta.url === `file://${process.argv[1]}`) runCli();