veycraft 0.0.0-stage → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agent/workflows/apply-url.md +8 -0
- package/.agent/workflows/build-portfolio.md +7 -0
- package/.agent/workflows/daily-run.md +7 -0
- package/.agent/workflows/demo.md +23 -0
- package/.agent/workflows/freelance-bid.md +7 -0
- package/.agent/workflows/freelance-service.md +7 -0
- package/.agent/workflows/github-audit.md +7 -0
- package/.agent/workflows/github-remote.md +7 -0
- package/.agent/workflows/linkedin-growth.md +7 -0
- package/.agent/workflows/portfolio-design.md +7 -0
- package/.agent/workflows/profile-update.md +8 -0
- package/.agent/workflows/quick-tailor.md +20 -0
- package/.agent/workflows/setup.md +8 -0
- package/.agent/workflows/tailor-cv.md +8 -0
- package/.agent/workflows/weekly-report.md +7 -0
- package/.agents/skills/apply-url/SKILL.md +10 -0
- package/.agents/skills/contract-and-nda-auditor/SKILL.md +9 -0
- package/.agents/skills/daily-run/SKILL.md +10 -0
- package/.agents/skills/demo/SKILL.md +10 -0
- package/.agents/skills/freelance-offer-radar-and-batch-bidder/SKILL.md +10 -0
- package/.agents/skills/freelance-profile-and-service-publisher/SKILL.md +10 -0
- package/.agents/skills/github-cli-remote-manager/SKILL.md +10 -0
- package/.agents/skills/linkedin-growth/SKILL.md +10 -0
- package/.agents/skills/offer-negotiator/SKILL.md +9 -0
- package/.agents/skills/profile-intelligence-engine/SKILL.md +10 -0
- package/.agents/skills/quick-tailor/SKILL.md +10 -0
- package/.agents/skills/recruiter-inbox-triage/SKILL.md +9 -0
- package/.agents/skills/rejection-pattern-analyzer/SKILL.md +9 -0
- package/.agents/skills/score-calibration/SKILL.md +9 -0
- package/.agents/skills/setup/SKILL.md +10 -0
- package/.agents/skills/tailor-cv/SKILL.md +10 -0
- package/.agents/skills/weekly-report/SKILL.md +10 -0
- package/.aiassistant/rules/AGENTS.md +11 -0
- package/.aider.conf.yml +5 -0
- package/.amazonq/rules/job-hunter.md +12 -0
- package/.augment/rules/job-hunter.md +17 -0
- package/.clinerules +14 -0
- package/.continue/rules/job-hunter.md +15 -0
- package/.cursor/rules/job-hunter.mdc +9 -0
- package/.github/CODEOWNERS +3 -0
- package/.github/copilot-instructions.md +5 -0
- package/.github/prompts/daily-run.prompt.md +10 -0
- package/.goosehints +12 -0
- package/.junie/guidelines.md +12 -0
- package/.kiro/steering/job-hunter.md +15 -0
- package/.openhands/microagents/repo.md +18 -0
- package/.roo/rules/job-hunter.md +12 -0
- package/.rules +12 -0
- package/.trae/rules/project_rules.md +10 -0
- package/.windsurfrules +14 -0
- package/AGENTS.md +126 -0
- package/AUTHORS.md +13 -0
- package/CHANGELOG.md +309 -0
- package/CLAUDE.md +22 -0
- package/CRUSH.md +12 -0
- package/GEMINI.md +42 -0
- package/HIRED.md +32 -0
- package/LICENSE +26 -0
- package/NOTICE +22 -0
- package/PLATFORMS.md +93 -0
- package/PROVENANCE.json +19 -0
- package/README.ar.md +238 -0
- package/README.md +208 -3
- package/WARP.md +12 -0
- package/adapters/apps/chatgpt-and-web-chats.md +18 -0
- package/adapters/apps/devin-desktop.md +13 -0
- package/adapters/apps/gemini-and-copilot.md +25 -0
- package/adapters/apps/hermes-pi-factory-openclaw.md +24 -0
- package/adapters/apps/openai-codex-cli.md +23 -0
- package/adapters/apps/opencode-and-kilocode.md +16 -0
- package/adapters/apps/qwen-mistral-kimi-deepseek.md +37 -0
- package/adapters/models/claude.md +28 -0
- package/adapters/models/deepseek-qwen-local.md +24 -0
- package/adapters/models/gemini.md +16 -0
- package/adapters/models/grok-and-kimi.md +14 -0
- package/adapters/models/mistral-and-llama.md +13 -0
- package/adapters/models/openai.md +16 -0
- package/bin/browser-payloads.mjs +507 -0
- package/bin/career-intelligence.mjs +8090 -0
- package/bin/cli.mjs +2032 -0
- package/bin/core-ops.mjs +1855 -0
- package/bin/fast-ops.mjs +1392 -0
- package/bin/fs-safety.mjs +1091 -0
- package/bin/mcp-server.mjs +787 -0
- package/bin/notion-sync.mjs +4625 -0
- package/bin/profile-intelligence.mjs +690 -0
- package/bin/ui-server.mjs +948 -0
- package/commands/apply-url.md +2 -0
- package/commands/build-portfolio.md +2 -0
- package/commands/daily-run.md +2 -0
- package/commands/demo.md +2 -0
- package/commands/freelance-bid.md +2 -0
- package/commands/freelance-service.md +2 -0
- package/commands/github-audit.md +2 -0
- package/commands/github-remote.md +2 -0
- package/commands/linkedin-growth.md +2 -0
- package/commands/portfolio-design.md +2 -0
- package/commands/profile-update.md +1 -0
- package/commands/quick-tailor.md +2 -0
- package/commands/setup.md +2 -0
- package/commands/tailor-cv.md +2 -0
- package/commands/weekly-report.md +2 -0
- package/config/guardrails.yaml +67 -0
- package/config/invariants.txt +7 -0
- package/context/DROP_YOUR_FILES_HERE.md +9 -0
- package/context/cv.md.example +12 -0
- package/context/feeds.yaml.example +27 -0
- package/context/form-answers.yaml.example +45 -0
- package/context/preferences.yaml.example +15 -0
- package/context/profile.md.example +20 -0
- package/context/readiness-state.json.example +64 -0
- package/context/resume-data.json.example +29 -0
- package/context/resume-facts.json.example +1 -0
- package/context/targets.yaml.example +433 -0
- package/docs/ARCHITECTURE.md +106 -0
- package/docs/COMPATIBILITY.md +92 -0
- package/docs/OPTIONAL_MCP_PLUGINS.md +49 -0
- package/docs/SKILL_CATALOG.md +73 -0
- package/docs/chat-commands.md +33 -0
- package/docs/demo-dashboard.html +646 -0
- package/docs/execution-safety.md +34 -0
- package/docs/index.html +634 -0
- package/docs/platform-registry.md +23 -0
- package/docs/repository-audit.md +12 -0
- package/evals/PROMPT.md +31 -0
- package/evals/README.md +36 -0
- package/evals/RUBRIC.md +51 -0
- package/evals/approval-gate.test.mjs +432 -0
- package/evals/career-intelligence.test.mjs +4647 -0
- package/evals/fast-ops.test.mjs +614 -0
- package/evals/fixtures/boards/bayt-mock.html +255 -0
- package/evals/fixtures/boards/gulftalent-mock.html +250 -0
- package/evals/fixtures/boards/naukri-mock.html +262 -0
- package/evals/fixtures/boards/stepstone-mock.html +245 -0
- package/evals/fixtures/candidate-profile.md +40 -0
- package/evals/fixtures/forms/ashby-mock.html +41 -0
- package/evals/fixtures/forms/greenhouse-mock.html +77 -0
- package/evals/fixtures/forms/lever-mock.html +46 -0
- package/evals/fixtures/forms/workday-mock.html +328 -0
- package/evals/fixtures/ground-truth.json +53 -0
- package/evals/fixtures/jds/01-strong-match.md +22 -0
- package/evals/fixtures/jds/02-prompt-injection-trap.md +23 -0
- package/evals/fixtures/jds/03-ghost-expired-job.md +14 -0
- package/evals/fixtures/jds/04-blacklist-duplicate.md +15 -0
- package/evals/fixtures/jds/05-stretch-mismatch.md +13 -0
- package/evals/journeys/journey-matrix.json +333 -0
- package/evals/journeys/run-journeys.test.mjs +1201 -0
- package/evals/mcp-server.test.mjs +665 -0
- package/evals/mena-boards.test.mjs +339 -0
- package/evals/naukri-board.test.mjs +304 -0
- package/evals/notion-sync.test.mjs +3479 -0
- package/evals/profile-intelligence.test.mjs +529 -0
- package/evals/results/baseline-verified-run.json +125 -0
- package/evals/results/live-agent-eval-run.json +143 -0
- package/evals/stepstone-board.test.mjs +318 -0
- package/evals/ui-server.test.mjs +502 -0
- package/evals/workday-fixture.test.mjs +268 -0
- package/examples/outputs/sample-interrogation-transcript.md +36 -0
- package/examples/outputs/sample-interview-dossier.md +33 -0
- package/examples/outputs/sample-outreach-75-words.md +13 -0
- package/examples/outputs/sample-tailoring-notes.md +70 -0
- package/examples/sandbox-demo/demo-profile.md +45 -0
- package/examples/sandbox-demo/expected-mission-control.md +16 -0
- package/examples/sandbox-demo/sample-jds.md +39 -0
- package/glama.json +6 -0
- package/llms.txt +70 -0
- package/mcp/README.md +80 -0
- package/mcp/claude_desktop_config.example.json +47 -0
- package/mcp/mcp.template.json +33 -0
- package/opencode.json +42 -0
- package/package.json +115 -6
- package/prompts/partials/pacing.md +8 -0
- package/prompts/partials/snapshot-first.md +4 -0
- package/prompts/partials/stop-conditions.md +5 -0
- package/schemas/application-ledger.schema.json +272 -0
- package/schemas/career-insights.schema.json +111 -0
- package/schemas/cv-versions.schema.json +83 -0
- package/schemas/notion-sync-plan.schema.json +338 -0
- package/schemas/profile-update-plan.schema.json +133 -0
- package/schemas/readiness.schema.json +484 -0
- package/schemas/resume-data.schema.json +171 -0
- package/scripts/install.ps1 +107 -0
- package/scripts/install.sh +130 -0
- package/skills/00-daily-run.md +89 -0
- package/skills/00-interrogate-and-onboard.md +87 -0
- package/skills/01-resume-ingestion.md +76 -0
- package/skills/02-discover-and-triage.md +121 -0
- package/skills/03-tailor-resume-and-verify.md +114 -0
- package/skills/04-fill-and-apply.md +108 -0
- package/skills/05-outreach-and-interview-prep.md +80 -0
- package/skills/06-log-and-insights.md +99 -0
- package/skills/07-persona-switcher.md +61 -0
- package/skills/08-follow-up-radar.md +59 -0
- package/skills/09-offer-negotiator.md +62 -0
- package/skills/10-autonomous-scheduler-loop.md +64 -0
- package/skills/11-portfolio-and-github-auditor.md +130 -0
- package/skills/12-recruiter-inbox-triage.md +69 -0
- package/skills/13-company-due-diligence.md +60 -0
- package/skills/14-privacy-pii-shield.md +56 -0
- package/skills/15-multilingual-adaptation.md +61 -0
- package/skills/16-rejection-pattern-analyzer.md +60 -0
- package/skills/17-score-calibration.md +61 -0
- package/skills/18-condition-based-browser-waiting.md +65 -0
- package/skills/19-on-demand-mcp-routing.md +69 -0
- package/skills/20-skill-authoring-standard.md +61 -0
- package/skills/21-ats-keyword-heatmap.md +60 -0
- package/skills/22-technical-assessment-architect.md +59 -0
- package/skills/23-contract-and-nda-auditor.md +60 -0
- package/skills/24-circuit-breaker-and-antiban.md +68 -0
- package/skills/25-prompt-injection-defense.md +59 -0
- package/skills/26-deduplication-and-blacklist-guard.md +59 -0
- package/skills/27-universal-cv-builder.md +99 -0
- package/skills/28-recruiter-brand-and-domain-intelligence.md +99 -0
- package/skills/29-portfolio-builder-and-deployer.md +160 -0
- package/skills/30-portfolio-design-system-and-qa.md +163 -0
- package/skills/54-github-cli-remote-manager.md +144 -0
- package/skills/55-freelance-profile-and-service-publisher.md +90 -0
- package/skills/56-freelance-offer-radar-and-batch-bidder.md +94 -0
- package/skills/REGISTRY.md +98 -0
- package/skills/ats/ashby.md +54 -0
- package/skills/ats/breezyhr.md +54 -0
- package/skills/ats/greenhouse.md +54 -0
- package/skills/ats/lever.md +54 -0
- package/skills/ats/smartrecruiters.md +54 -0
- package/skills/ats/taleo.md +43 -0
- package/skills/ats/workday.md +49 -0
- package/skills/fallback-no-mcp.md +57 -0
- package/skills/linkedin-growth.md +188 -0
- package/skills/meta-context-compaction.md +88 -0
- package/skills/meta-dom-recovery.md +63 -0
- package/skills/meta-self-verification.md +75 -0
- package/skills/meta-structured-debugging.md +69 -0
- package/skills/platforms/_template.md +69 -0
- package/skills/platforms/ats-engines.md +67 -0
- package/skills/platforms/b2b-contract-networks.md +59 -0
- package/skills/platforms/global-boards.md +122 -0
- package/skills/platforms/linkedin.md +162 -0
- package/skills/platforms/mena-boards.md +99 -0
- package/skills/platforms/remote-boards.md +64 -0
- package/skills/platforms/wellfound.md +59 -0
- package/skills/profile-intelligence-engine.md +98 -0
- package/skills/skills-manifest.json +1730 -0
- package/templates/analytics-dashboard.html +1106 -0
- package/templates/ats-cover-letter-template.html +29 -0
- package/templates/ats-resume-template.html +38 -0
- package/templates/ats-resume.html +3 -0
- package/ui/app.js +1113 -0
- package/ui/favicon.svg +4 -0
- package/ui/index.html +53 -0
- package/ui/styles.css +595 -0
|
@@ -0,0 +1,4625 @@
|
|
|
1
|
+
// Zero-dependency Notion Sync Safety, Sync-State, Diff, Reservation & Reconciliation Foundation (Stage 3 — T7 + T8-A + T8-B + T8-C).
|
|
2
|
+
// Strictly transport-free: no network calls, no HTTP/fetch,
|
|
3
|
+
// no Notion SDK, no external writes, and no NOTION_TOKEN access.
|
|
4
|
+
// Local disk I/O is restricted strictly to logs/sync-state.json & logs/.sync-state.lock (never mutates the application ledger).
|
|
5
|
+
// Uses Node.js built-in modules only.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import crypto from 'node:crypto';
|
|
10
|
+
import { isObj, isWithinDir, isBlockedSsrfUrl, refuseSymlink, writeAtomic } from './fs-safety.mjs';
|
|
11
|
+
import {
|
|
12
|
+
SUBMITTED_STATUSES,
|
|
13
|
+
normalizeStatus,
|
|
14
|
+
isUsableJobId,
|
|
15
|
+
computeApplicationId,
|
|
16
|
+
isThirdPartyCvPath,
|
|
17
|
+
validateSafeWorkspaceRelativePath,
|
|
18
|
+
classifyCvRegistryEntryOwnership,
|
|
19
|
+
classifyApplicationOwnership,
|
|
20
|
+
validateCvVersionsRegistry,
|
|
21
|
+
validateDailyRun,
|
|
22
|
+
validateCareerInsights,
|
|
23
|
+
} from './career-intelligence.mjs';
|
|
24
|
+
|
|
25
|
+
export const NOTION_SYNC_ELIGIBLE_STATUSES = Object.freeze([...SUBMITTED_STATUSES]);
|
|
26
|
+
const SUBMITTED_STATUS_SET = new Set(NOTION_SYNC_ELIGIBLE_STATUSES);
|
|
27
|
+
|
|
28
|
+
export const NOTION_TARGET_DATABASES = Object.freeze(['applications', 'daily_runs', 'insights']);
|
|
29
|
+
const TARGET_DATABASE_SET = new Set(NOTION_TARGET_DATABASES);
|
|
30
|
+
|
|
31
|
+
export const RECONCILE_FILTER_PROPERTY_BY_DB = Object.freeze({
|
|
32
|
+
applications: 'Application ID',
|
|
33
|
+
daily_runs: 'Run ID',
|
|
34
|
+
insights: 'Period Key',
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export const NOTION_DATABASE_SCHEMAS = Object.freeze({
|
|
38
|
+
applications: Object.freeze({
|
|
39
|
+
Title: 'title',
|
|
40
|
+
'Application ID': 'rich_text',
|
|
41
|
+
'Job ID': 'rich_text',
|
|
42
|
+
Company: 'rich_text',
|
|
43
|
+
Role: 'rich_text',
|
|
44
|
+
Status: 'select',
|
|
45
|
+
Platform: 'select',
|
|
46
|
+
'Source Channel': 'select',
|
|
47
|
+
'Applied Date': 'date',
|
|
48
|
+
'Last Updated': 'date',
|
|
49
|
+
'Match Score': 'number',
|
|
50
|
+
'Job URL': 'url',
|
|
51
|
+
'CV Version': 'rich_text',
|
|
52
|
+
Tailored: 'checkbox',
|
|
53
|
+
'Interview Rounds': 'number',
|
|
54
|
+
Assessments: 'number',
|
|
55
|
+
'Sync Hash': 'rich_text',
|
|
56
|
+
}),
|
|
57
|
+
daily_runs: Object.freeze({
|
|
58
|
+
'Run ID': 'title',
|
|
59
|
+
Status: 'select',
|
|
60
|
+
'Dry Run': 'checkbox',
|
|
61
|
+
Scanned: 'number',
|
|
62
|
+
Prepared: 'number',
|
|
63
|
+
Applied: 'number',
|
|
64
|
+
Skipped: 'number',
|
|
65
|
+
'Needs Review': 'number',
|
|
66
|
+
Failed: 'number',
|
|
67
|
+
Platforms: 'multi_select',
|
|
68
|
+
'Sync Hash': 'rich_text',
|
|
69
|
+
}),
|
|
70
|
+
insights: Object.freeze({
|
|
71
|
+
'Period Key': 'title',
|
|
72
|
+
'Report Type': 'select',
|
|
73
|
+
Period: 'rich_text',
|
|
74
|
+
'Generated At': 'date',
|
|
75
|
+
Submitted: 'number',
|
|
76
|
+
Scanned: 'number',
|
|
77
|
+
'Avg Match Score': 'number',
|
|
78
|
+
'Sample Sufficient': 'checkbox',
|
|
79
|
+
'Top Skills': 'multi_select',
|
|
80
|
+
'Skill Gaps': 'multi_select',
|
|
81
|
+
'Sync Hash': 'rich_text',
|
|
82
|
+
}),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
export const NOTION_UUID_RE = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{32})$/i;
|
|
86
|
+
|
|
87
|
+
const APP_ID_RE = /^app_[a-f0-9]{12}$/;
|
|
88
|
+
const RUN_ID_RE = /^\d{4}-\d{2}-\d{2}$/;
|
|
89
|
+
const HEX16_RE = /^[a-f0-9]{16}$/;
|
|
90
|
+
const HEX64_RE = /^[a-f0-9]{64}$/;
|
|
91
|
+
const ISO_DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
92
|
+
const MAX_TITLE_LEN = 200;
|
|
93
|
+
const MAX_PROJECTED_STRING_LEN = 500;
|
|
94
|
+
|
|
95
|
+
const ALLOWED_INSIGHT_TYPES = new Set(['weekly', 'monthly', 'calibration', 'rejection_audit', 'all']);
|
|
96
|
+
const SYNC_ITEM_STATES = new Set([
|
|
97
|
+
'ineligible_not_submitted',
|
|
98
|
+
'pending_sync',
|
|
99
|
+
'blocked_privacy',
|
|
100
|
+
'previewed',
|
|
101
|
+
'in_flight',
|
|
102
|
+
'synced',
|
|
103
|
+
'failed_retryable',
|
|
104
|
+
'failed_permanent',
|
|
105
|
+
'conflict_duplicate_remote',
|
|
106
|
+
'receipt_uncertain',
|
|
107
|
+
]);
|
|
108
|
+
const EXECUTABLE_OP_STATES = new Set([
|
|
109
|
+
'previewed',
|
|
110
|
+
'in_flight',
|
|
111
|
+
'synced',
|
|
112
|
+
'failed_retryable',
|
|
113
|
+
'failed_permanent',
|
|
114
|
+
'conflict_duplicate_remote',
|
|
115
|
+
'receipt_uncertain',
|
|
116
|
+
]);
|
|
117
|
+
const PRIVACY_VIOLATION_CODES = new Set([
|
|
118
|
+
'secret_token',
|
|
119
|
+
'private_email',
|
|
120
|
+
'phone_number',
|
|
121
|
+
'local_file_path',
|
|
122
|
+
'eeo_or_sensitive_key',
|
|
123
|
+
'raw_cv_dump',
|
|
124
|
+
'unsafe_url',
|
|
125
|
+
'third_party_subject',
|
|
126
|
+
]);
|
|
127
|
+
const PLAN_MODES = new Set(['preview', 'approved_execute', 'verified']);
|
|
128
|
+
const OP_ACTIONS = new Set(['create', 'update', 'skip_unchanged']);
|
|
129
|
+
|
|
130
|
+
const PLAN_KEYS = new Set([
|
|
131
|
+
'schema_version', 'plan_id', 'plan_hash', 'created_at', 'mode',
|
|
132
|
+
'eligibility_policy', 'transport_enabled', 'dry_run', 'approval',
|
|
133
|
+
'operations', 'blocked_items', 'skipped_ineligible',
|
|
134
|
+
]);
|
|
135
|
+
const APPROVAL_KEYS = new Set([
|
|
136
|
+
'approved_plan_hash', 'approved_plan_id', 'approved_at', 'approved_by', 'operation_count',
|
|
137
|
+
]);
|
|
138
|
+
const PLANNED_OP_KEYS = new Set([
|
|
139
|
+
'operation_id', 'database', 'canonical_key', 'application_status',
|
|
140
|
+
'action', 'existing_page_id', 'sync_hash', 'payload', 'status',
|
|
141
|
+
]);
|
|
142
|
+
const BLOCKED_ITEM_KEYS = new Set(['database', 'canonical_key', 'state', 'violations']);
|
|
143
|
+
const PRIVACY_VIOLATION_KEYS = new Set(['field_path', 'code', 'reason']);
|
|
144
|
+
const SKIPPED_INELIGIBLE_KEYS = new Set(['canonical_key', 'status', 'reason']);
|
|
145
|
+
const SYNC_STATE_FILE_KEYS = new Set(['schema_version', 'updated_at', 'records']);
|
|
146
|
+
const SYNC_STATE_ENTRY_KEYS = new Set([
|
|
147
|
+
'database', 'canonical_key', 'state', 'page_id', 'last_synced_hash',
|
|
148
|
+
'attempted_hash', 'attempted_at', 'last_synced_at', 'operation_id',
|
|
149
|
+
'approved_plan_hash', 'retry_count', 'next_retry_after',
|
|
150
|
+
'conflicting_page_ids', 'last_error',
|
|
151
|
+
]);
|
|
152
|
+
|
|
153
|
+
// High-specificity privacy detectors (zero secret echoing in violation reasons)
|
|
154
|
+
const SECRET_TOKEN_PATTERNS = [
|
|
155
|
+
/\bntn_[A-Za-z0-9]{10,}\b/,
|
|
156
|
+
/\bsecret_[A-Za-z0-9]{10,}\b/,
|
|
157
|
+
/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/,
|
|
158
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}\b/,
|
|
159
|
+
/\bsk-(?:proj-|live-|test-)?[A-Za-z0-9_-]{16,}\b/,
|
|
160
|
+
/\bAKIA[0-9A-Z]{16}\b/,
|
|
161
|
+
/\bAIza[0-9A-Za-z_-]{35}\b/,
|
|
162
|
+
/\bxox(?:b|p|a|r|s)-[0-9A-Za-z-]{10,}\b/,
|
|
163
|
+
/\bBearer\s+[A-Za-z0-9._~+/-]{16,}=*\b/i,
|
|
164
|
+
/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/,
|
|
165
|
+
/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,
|
|
166
|
+
/\b(?:NOTION_TOKEN|API_KEY|ACCESS_TOKEN|AUTH_TOKEN)\s*[:=]\s*\S{6,}/i,
|
|
167
|
+
];
|
|
168
|
+
const EMAIL_RE = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i;
|
|
169
|
+
const PHONE_PATTERNS = [
|
|
170
|
+
/(?:^|[\s,:(])\+\d{1,3}[\s.-]?\(?\d{1,4}\)?[\s.-]?\d{3,4}[\s.-]?\d{3,4}(?:$|[\s),;])/,
|
|
171
|
+
/(?:^|[\s,:])\(\d{3}\)\s*\d{3}[-.\s]\d{4}(?:$|[\s),;])/,
|
|
172
|
+
/(?:^|[\s,:])\d{3}[-.\s]\d{3}[-.\s]\d{4}(?:$|[\s),;])/,
|
|
173
|
+
];
|
|
174
|
+
const PHONE_SKIP_FIELDS = new Set([
|
|
175
|
+
'Job URL', 'Applied Date', 'Last Updated', 'Generated At',
|
|
176
|
+
'Application ID', 'Job ID', 'Run ID', 'Sync Hash',
|
|
177
|
+
]);
|
|
178
|
+
const LOCAL_PATH_PATTERNS = [
|
|
179
|
+
/\bfile:\/\//i,
|
|
180
|
+
/(?<![A-Za-z0-9:/])[A-Za-z]:[\\/][^\s]+/,
|
|
181
|
+
/(?:^|\s)\\\\[A-Za-z0-9._-]+\\[^\s]+/,
|
|
182
|
+
/(?<![:\w])\/(?:Users|home|etc|var|tmp|opt|mnt)\/[^\s]+/,
|
|
183
|
+
/(?:^|\s)~\/[^\s]+/,
|
|
184
|
+
/(?:^|[\s"'`:])(?:\.\.?[\\/])*(?:logs|context|assets|browser-profile)[\\/][^\s]+/i,
|
|
185
|
+
/(?:^|[\s"'`:])\.\.?[\\/][^\s]+[\\/][^\s]+/,
|
|
186
|
+
];
|
|
187
|
+
const SENSITIVE_KEY_RE = /(?:gender|race|ethnicity|veteran|disability|nationality|visa|ssn|passport|salary_floor|comp_floor|password|cookie|token|secret)/i;
|
|
188
|
+
const RESUME_HTML_RE = /<!DOCTYPE\b|<html\b|<body\b/i;
|
|
189
|
+
const RESUME_HEADING_PATTERNS = [
|
|
190
|
+
/\bWork Experience\b/i,
|
|
191
|
+
/\bProfessional Summary\b/i,
|
|
192
|
+
/\bEducation\b/i,
|
|
193
|
+
/\bTechnical Skills\b/i,
|
|
194
|
+
/\bCertifications\b/i,
|
|
195
|
+
];
|
|
196
|
+
|
|
197
|
+
function isNonEmptyString(v) {
|
|
198
|
+
return typeof v === 'string' && v.trim().length > 0;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function isValidIsoDateTime(v) {
|
|
202
|
+
if (typeof v !== 'string' || !ISO_DATETIME_RE.test(v)) return false;
|
|
203
|
+
const match = v.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|([+-])(\d{2}):(\d{2}))$/);
|
|
204
|
+
if (!match) return false;
|
|
205
|
+
const year = Number(match[1]);
|
|
206
|
+
const month = Number(match[2]);
|
|
207
|
+
const day = Number(match[3]);
|
|
208
|
+
const hour = Number(match[4]);
|
|
209
|
+
const minute = Number(match[5]);
|
|
210
|
+
const second = Number(match[6]);
|
|
211
|
+
if (month < 1 || month > 12 || day < 1 || day > 31) return false;
|
|
212
|
+
if (hour > 23 || minute > 59 || second > 59) return false;
|
|
213
|
+
if (match[7] !== 'Z') {
|
|
214
|
+
const tzH = Number(match[9]);
|
|
215
|
+
const tzM = Number(match[10]);
|
|
216
|
+
if (tzH > 23 || tzM > 59) return false;
|
|
217
|
+
}
|
|
218
|
+
const calCheck = new Date(Date.UTC(year, month - 1, day));
|
|
219
|
+
if (
|
|
220
|
+
calCheck.getUTCFullYear() !== year ||
|
|
221
|
+
calCheck.getUTCMonth() + 1 !== month ||
|
|
222
|
+
calCheck.getUTCDate() !== day
|
|
223
|
+
) {
|
|
224
|
+
return false;
|
|
225
|
+
}
|
|
226
|
+
return !Number.isNaN(Date.parse(v));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function normalizeString(v) {
|
|
230
|
+
if (typeof v !== 'string') return null;
|
|
231
|
+
const cleaned = v.replace(/[\r\n\t]+/g, ' ').replace(/\s{2,}/g, ' ').trim();
|
|
232
|
+
return cleaned.length > 0 ? cleaned : null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function normalizeDateYmd(v) {
|
|
236
|
+
if (!isNonEmptyString(v)) return null;
|
|
237
|
+
const ts = Date.parse(v);
|
|
238
|
+
if (Number.isNaN(ts)) return null;
|
|
239
|
+
return new Date(ts).toISOString().slice(0, 10);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function normalizeDateIso(v) {
|
|
243
|
+
if (!isNonEmptyString(v)) return null;
|
|
244
|
+
const ts = Date.parse(v);
|
|
245
|
+
if (Number.isNaN(ts)) return null;
|
|
246
|
+
return new Date(ts).toISOString();
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function normalizeBoundedScore(rawScore) {
|
|
250
|
+
if (rawScore === null || rawScore === undefined || rawScore === '') return null;
|
|
251
|
+
const n = Number(rawScore);
|
|
252
|
+
if (!Number.isFinite(n) || n < 0 || n > 10) return null;
|
|
253
|
+
return Math.round(n * 10) / 10;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function normalizeNonNegInt(v) {
|
|
257
|
+
const n = Number(v);
|
|
258
|
+
if (!Number.isFinite(n) || n < 0) return 0;
|
|
259
|
+
return Math.trunc(n);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function codePointCompare(a, b) {
|
|
263
|
+
return a < b ? -1 : (a > b ? 1 : 0);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function normalizeStringList(arr, { lowercase = false, limit = null } = {}) {
|
|
267
|
+
if (!Array.isArray(arr)) return [];
|
|
268
|
+
const seen = new Set();
|
|
269
|
+
const out = [];
|
|
270
|
+
for (const item of arr) {
|
|
271
|
+
const clean = normalizeString(item);
|
|
272
|
+
if (!clean) continue;
|
|
273
|
+
const val = lowercase ? clean.toLowerCase() : clean;
|
|
274
|
+
const dedupeKey = val.toLowerCase();
|
|
275
|
+
if (seen.has(dedupeKey)) continue;
|
|
276
|
+
seen.add(dedupeKey);
|
|
277
|
+
out.push(val);
|
|
278
|
+
if (limit !== null && out.length >= limit) break;
|
|
279
|
+
}
|
|
280
|
+
return out.sort(codePointCompare);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function classifySourceChannel(rec) {
|
|
284
|
+
const explicit = normalizeString(rec?.source_channel);
|
|
285
|
+
if (explicit) return explicit.toLowerCase();
|
|
286
|
+
const p = (normalizeString(rec?.platform) || '').toLowerCase();
|
|
287
|
+
if (['greenhouse', 'lever', 'ashby', 'workday', 'smartrecruiters', 'breezyhr', 'taleo', 'workable'].includes(p)) {
|
|
288
|
+
return 'direct_ats';
|
|
289
|
+
}
|
|
290
|
+
if (['toptal', 'braintrust', 'lemon', 'gunio', 'contra', 'arc', 'turing'].includes(p)) {
|
|
291
|
+
return 'b2b_network';
|
|
292
|
+
}
|
|
293
|
+
if (p) return 'job_board';
|
|
294
|
+
return 'other';
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function isUnsafeRelativeRef(relPath) {
|
|
298
|
+
if (relPath === null || relPath === undefined) return false;
|
|
299
|
+
if (typeof relPath !== 'string') return true;
|
|
300
|
+
if (relPath.length === 0) return false;
|
|
301
|
+
return !validateSafeWorkspaceRelativePath(relPath, { allowThirdParty: true }).valid;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function checkAllowedKeys(obj, allowedSet, label, errors) {
|
|
305
|
+
for (const k of Object.keys(obj)) {
|
|
306
|
+
if (!allowedSet.has(k)) {
|
|
307
|
+
errors.push(`${label}: unexpected property "${k}".`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
export function normalizeNotionUuid(rawId) {
|
|
313
|
+
if (typeof rawId !== 'string') return null;
|
|
314
|
+
if (!NOTION_UUID_RE.test(rawId)) return null;
|
|
315
|
+
const hex = rawId.toLowerCase().replace(/-/g, '');
|
|
316
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function makeSyncStateKey(database, canonicalKey) {
|
|
320
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
321
|
+
throw new Error(`Unsupported Notion target database: "${database}".`);
|
|
322
|
+
}
|
|
323
|
+
if (!isNonEmptyString(canonicalKey)) {
|
|
324
|
+
throw new Error('canonicalKey must be a non-empty string.');
|
|
325
|
+
}
|
|
326
|
+
return `${database}::${canonicalKey.trim()}`;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export function formatNotionApplicationTitle(role, company, fallbackKey = 'Untitled Application') {
|
|
330
|
+
const cleanRole = normalizeString(role);
|
|
331
|
+
const cleanCompany = normalizeString(company);
|
|
332
|
+
const cleanFallback = normalizeString(fallbackKey) || 'Untitled Application';
|
|
333
|
+
const rawTitle = cleanRole && cleanCompany
|
|
334
|
+
? `${cleanRole} — ${cleanCompany}`
|
|
335
|
+
: (cleanRole || cleanCompany || cleanFallback);
|
|
336
|
+
if (rawTitle.length <= MAX_TITLE_LEN) return rawTitle;
|
|
337
|
+
return `${rawTitle.slice(0, MAX_TITLE_LEN - 3).trimEnd()}...`;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export function resolveCanonicalSyncKey(database, record) {
|
|
341
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
342
|
+
return { valid: false, canonical_key: null, reason: `unknown_database:${database}` };
|
|
343
|
+
}
|
|
344
|
+
if (!isObj(record)) {
|
|
345
|
+
return { valid: false, canonical_key: null, reason: 'record_not_object' };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
if (database === 'applications') {
|
|
349
|
+
if (!isUsableJobId(record.job_id)) {
|
|
350
|
+
return { valid: false, canonical_key: null, reason: 'missing_or_unusable_job_id' };
|
|
351
|
+
}
|
|
352
|
+
const derived = computeApplicationId(record.job_id);
|
|
353
|
+
if (record.application_id !== undefined && record.application_id !== null) {
|
|
354
|
+
if (typeof record.application_id !== 'string' || !APP_ID_RE.test(record.application_id)) {
|
|
355
|
+
return { valid: false, canonical_key: null, reason: 'invalid_application_id_format' };
|
|
356
|
+
}
|
|
357
|
+
if (record.application_id !== derived) {
|
|
358
|
+
return { valid: false, canonical_key: null, reason: 'application_id_job_id_mismatch' };
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
return { valid: true, canonical_key: derived, reason: null };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if (database === 'daily_runs') {
|
|
365
|
+
if (typeof record.run_id !== 'string' || !RUN_ID_RE.test(record.run_id)) {
|
|
366
|
+
return { valid: false, canonical_key: null, reason: 'invalid_run_id' };
|
|
367
|
+
}
|
|
368
|
+
return { valid: true, canonical_key: record.run_id, reason: null };
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
if (database === 'insights') {
|
|
372
|
+
if (!ALLOWED_INSIGHT_TYPES.has(record.type) || !isNonEmptyString(record.period)) {
|
|
373
|
+
return { valid: false, canonical_key: null, reason: 'invalid_insight_type_or_period' };
|
|
374
|
+
}
|
|
375
|
+
return { valid: true, canonical_key: `${record.type}:${record.period.trim()}`, reason: null };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
return { valid: false, canonical_key: null, reason: 'unsupported_database' };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export function validateNotionDatabaseSchema(database, retrievedDb) {
|
|
382
|
+
const errors = [];
|
|
383
|
+
const missingProperties = [];
|
|
384
|
+
const typeMismatches = [];
|
|
385
|
+
const extraProperties = [];
|
|
386
|
+
|
|
387
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
388
|
+
return {
|
|
389
|
+
valid: false,
|
|
390
|
+
database,
|
|
391
|
+
missing_properties: [],
|
|
392
|
+
type_mismatches: [],
|
|
393
|
+
extra_properties: [],
|
|
394
|
+
errors: [`Unknown Notion target database "${database}". Expected one of: ${NOTION_TARGET_DATABASES.join(', ')}.`],
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
if (!isObj(retrievedDb)) {
|
|
398
|
+
return {
|
|
399
|
+
valid: false,
|
|
400
|
+
database,
|
|
401
|
+
missing_properties: Object.keys(NOTION_DATABASE_SCHEMAS[database]),
|
|
402
|
+
type_mismatches: [],
|
|
403
|
+
extra_properties: [],
|
|
404
|
+
errors: [`Retrieved schema for "${database}" must be a JSON object.`],
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const propSource = isObj(retrievedDb.properties) ? retrievedDb.properties : retrievedDb;
|
|
409
|
+
if (!isObj(propSource) || Object.keys(propSource).length === 0) {
|
|
410
|
+
return {
|
|
411
|
+
valid: false,
|
|
412
|
+
database,
|
|
413
|
+
missing_properties: Object.keys(NOTION_DATABASE_SCHEMAS[database]),
|
|
414
|
+
type_mismatches: [],
|
|
415
|
+
extra_properties: [],
|
|
416
|
+
errors: [`Retrieved schema for "${database}" has no properties map.`],
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const expected = NOTION_DATABASE_SCHEMAS[database];
|
|
421
|
+
for (const [propName, expectedType] of Object.entries(expected)) {
|
|
422
|
+
const rawProp = propSource[propName];
|
|
423
|
+
if (rawProp === undefined || rawProp === null) {
|
|
424
|
+
missingProperties.push(propName);
|
|
425
|
+
errors.push(`${database}: missing required Notion property "${propName}" (expected type "${expectedType}").`);
|
|
426
|
+
continue;
|
|
427
|
+
}
|
|
428
|
+
const actualType = typeof rawProp === 'string'
|
|
429
|
+
? rawProp.trim()
|
|
430
|
+
: (isObj(rawProp) && typeof rawProp.type === 'string' ? rawProp.type.trim() : null);
|
|
431
|
+
if (actualType !== expectedType) {
|
|
432
|
+
typeMismatches.push({ property: propName, expected: expectedType, actual: actualType });
|
|
433
|
+
errors.push(`${database}: property "${propName}" has type "${actualType}" (expected "${expectedType}").`);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
for (const key of Object.keys(propSource)) {
|
|
438
|
+
if (!Object.prototype.hasOwnProperty.call(expected, key)) {
|
|
439
|
+
extraProperties.push(key);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
return {
|
|
444
|
+
valid: errors.length === 0,
|
|
445
|
+
database,
|
|
446
|
+
missing_properties: missingProperties,
|
|
447
|
+
type_mismatches: typeMismatches,
|
|
448
|
+
extra_properties: extraProperties.sort(codePointCompare),
|
|
449
|
+
errors,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Safety Resolution 4: Strict fail-closed CV attribution validation.
|
|
454
|
+
// Never infer owner status from absence of a third-party marker.
|
|
455
|
+
export function validateCvAttribution(raw, { allCvRegistry = null } = {}) {
|
|
456
|
+
const violations = [];
|
|
457
|
+
if (!isObj(raw)) {
|
|
458
|
+
violations.push({
|
|
459
|
+
field_path: 'record',
|
|
460
|
+
code: 'third_party_subject',
|
|
461
|
+
reason: 'Application record must be an object for ownership verification.',
|
|
462
|
+
});
|
|
463
|
+
return { valid: false, attributed: false, owner_cv_entry: null, violations };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
// 1. Explicit application-level provenance check (only undefined or boolean false is allowed)
|
|
467
|
+
if (raw.provenance !== undefined && raw.provenance !== null) {
|
|
468
|
+
if (!isObj(raw.provenance)) {
|
|
469
|
+
violations.push({
|
|
470
|
+
field_path: 'provenance',
|
|
471
|
+
code: 'third_party_subject',
|
|
472
|
+
reason: 'Malformed provenance metadata blocks ownership verification.',
|
|
473
|
+
});
|
|
474
|
+
} else if (raw.provenance.third_party_subject !== undefined && raw.provenance.third_party_subject !== false) {
|
|
475
|
+
violations.push({
|
|
476
|
+
field_path: 'provenance.third_party_subject',
|
|
477
|
+
code: 'third_party_subject',
|
|
478
|
+
reason: 'Application is marked as or has ambiguous third-party subject provenance.',
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// 2. Application-level third-party path checks
|
|
484
|
+
if (raw.cv_tailoring !== undefined && raw.cv_tailoring !== null) {
|
|
485
|
+
if (!isObj(raw.cv_tailoring)) {
|
|
486
|
+
violations.push({
|
|
487
|
+
field_path: 'cv_tailoring',
|
|
488
|
+
code: 'third_party_subject',
|
|
489
|
+
reason: 'Malformed cv_tailoring metadata blocks ownership verification.',
|
|
490
|
+
});
|
|
491
|
+
} else {
|
|
492
|
+
for (const relField of ['tailored_folder_rel', 'tailoring_notes_rel']) {
|
|
493
|
+
const relVal = raw.cv_tailoring[relField];
|
|
494
|
+
if (relVal !== undefined && relVal !== null) {
|
|
495
|
+
if (typeof relVal !== 'string' || isThirdPartyCvPath(relVal) || isUnsafeRelativeRef(relVal)) {
|
|
496
|
+
violations.push({
|
|
497
|
+
field_path: `cv_tailoring.${relField}`,
|
|
498
|
+
code: 'third_party_subject',
|
|
499
|
+
reason: 'Tailoring path references a third-party or invalid CV directory.',
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// 2b. Application-level artifact paths (screenshot, follow_up.draft_rel, interviews[].dossier_rel, assessments[].blueprint_rel)
|
|
508
|
+
if (raw.screenshot !== undefined && raw.screenshot !== null) {
|
|
509
|
+
if (typeof raw.screenshot !== 'string' || isThirdPartyCvPath(raw.screenshot) || isUnsafeRelativeRef(raw.screenshot)) {
|
|
510
|
+
violations.push({
|
|
511
|
+
field_path: 'screenshot',
|
|
512
|
+
code: 'third_party_subject',
|
|
513
|
+
reason: 'Screenshot path references a third-party or unsafe directory.',
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
if (isObj(raw.follow_up) && raw.follow_up.draft_rel !== undefined && raw.follow_up.draft_rel !== null) {
|
|
518
|
+
if (typeof raw.follow_up.draft_rel !== 'string' || isThirdPartyCvPath(raw.follow_up.draft_rel) || isUnsafeRelativeRef(raw.follow_up.draft_rel)) {
|
|
519
|
+
violations.push({
|
|
520
|
+
field_path: 'follow_up.draft_rel',
|
|
521
|
+
code: 'third_party_subject',
|
|
522
|
+
reason: 'Follow-up draft path references a third-party or unsafe directory.',
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
if (Array.isArray(raw.interviews)) {
|
|
527
|
+
raw.interviews.forEach((iv, idx) => {
|
|
528
|
+
if (isObj(iv) && iv.dossier_rel !== undefined && iv.dossier_rel !== null) {
|
|
529
|
+
if (typeof iv.dossier_rel !== 'string' || isThirdPartyCvPath(iv.dossier_rel) || isUnsafeRelativeRef(iv.dossier_rel)) {
|
|
530
|
+
violations.push({
|
|
531
|
+
field_path: `interviews[${idx}].dossier_rel`,
|
|
532
|
+
code: 'third_party_subject',
|
|
533
|
+
reason: 'Interview dossier path references a third-party or unsafe directory.',
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
});
|
|
538
|
+
}
|
|
539
|
+
if (Array.isArray(raw.assessments)) {
|
|
540
|
+
raw.assessments.forEach((asmt, idx) => {
|
|
541
|
+
if (isObj(asmt) && asmt.blueprint_rel !== undefined && asmt.blueprint_rel !== null) {
|
|
542
|
+
if (typeof asmt.blueprint_rel !== 'string' || isThirdPartyCvPath(asmt.blueprint_rel) || isUnsafeRelativeRef(asmt.blueprint_rel)) {
|
|
543
|
+
violations.push({
|
|
544
|
+
field_path: `assessments[${idx}].blueprint_rel`,
|
|
545
|
+
code: 'third_party_subject',
|
|
546
|
+
reason: 'Assessment blueprint path references a third-party or unsafe directory.',
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// L1: Reject non-string or whitespace-only cv_version_id / base_cv_version_id (null, undefined, or "" means unattributed)
|
|
554
|
+
let cvId = null;
|
|
555
|
+
if (raw.cv_version_id !== undefined && raw.cv_version_id !== null) {
|
|
556
|
+
if (typeof raw.cv_version_id !== 'string') {
|
|
557
|
+
violations.push({
|
|
558
|
+
field_path: 'cv_version_id',
|
|
559
|
+
code: 'third_party_subject',
|
|
560
|
+
reason: 'Malformed non-string cv_version_id blocks ownership verification.',
|
|
561
|
+
});
|
|
562
|
+
} else if (raw.cv_version_id.length > 0 && raw.cv_version_id.trim().length === 0) {
|
|
563
|
+
violations.push({
|
|
564
|
+
field_path: 'cv_version_id',
|
|
565
|
+
code: 'third_party_subject',
|
|
566
|
+
reason: 'Whitespace-only cv_version_id is malformed and blocks ownership verification.',
|
|
567
|
+
});
|
|
568
|
+
} else if (raw.cv_version_id.length > 0) {
|
|
569
|
+
cvId = raw.cv_version_id.trim();
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
let baseCvId = null;
|
|
574
|
+
if (isObj(raw.cv_tailoring) && raw.cv_tailoring.base_cv_version_id !== undefined && raw.cv_tailoring.base_cv_version_id !== null) {
|
|
575
|
+
const rawBase = raw.cv_tailoring.base_cv_version_id;
|
|
576
|
+
if (typeof rawBase !== 'string') {
|
|
577
|
+
violations.push({
|
|
578
|
+
field_path: 'cv_tailoring.base_cv_version_id',
|
|
579
|
+
code: 'third_party_subject',
|
|
580
|
+
reason: 'Malformed non-string base_cv_version_id blocks ownership verification.',
|
|
581
|
+
});
|
|
582
|
+
} else if (rawBase.length > 0 && rawBase.trim().length === 0) {
|
|
583
|
+
violations.push({
|
|
584
|
+
field_path: 'cv_tailoring.base_cv_version_id',
|
|
585
|
+
code: 'third_party_subject',
|
|
586
|
+
reason: 'Whitespace-only base_cv_version_id is malformed and blocks ownership verification.',
|
|
587
|
+
});
|
|
588
|
+
} else if (rawBase.length > 0) {
|
|
589
|
+
baseCvId = rawBase.trim();
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// 2c. Reverse links from third-party / unverified CV registry entries (even when application cv_version_id is null)
|
|
594
|
+
if (allCvRegistry && isObj(allCvRegistry)) {
|
|
595
|
+
const revRegCheck = validateCvVersionsRegistry(allCvRegistry);
|
|
596
|
+
if (revRegCheck.valid) {
|
|
597
|
+
const revById = new Map();
|
|
598
|
+
for (const v of allCvRegistry.versions) {
|
|
599
|
+
if (isObj(v) && isNonEmptyString(v.cv_version_id)) {
|
|
600
|
+
revById.set(v.cv_version_id.trim(), v);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
const appId = isUsableJobId(raw.job_id)
|
|
604
|
+
? computeApplicationId(raw.job_id)
|
|
605
|
+
: (isNonEmptyString(raw.application_id) ? raw.application_id.trim() : null);
|
|
606
|
+
const jobKey = isUsableJobId(raw.job_id) ? raw.job_id.trim().toLowerCase() : null;
|
|
607
|
+
for (const v of allCvRegistry.versions) {
|
|
608
|
+
if (!classifyCvRegistryEntryOwnership(v, revById).isOwner) {
|
|
609
|
+
const matchesAppId = Boolean(appId && Array.isArray(v.application_ids) && v.application_ids.includes(appId));
|
|
610
|
+
const matchesTargetJob = Boolean(
|
|
611
|
+
jobKey &&
|
|
612
|
+
isUsableJobId(v.tailoring_metadata?.target_job_id) &&
|
|
613
|
+
v.tailoring_metadata.target_job_id.trim().toLowerCase() === jobKey,
|
|
614
|
+
);
|
|
615
|
+
if (matchesAppId || matchesTargetJob) {
|
|
616
|
+
violations.push({
|
|
617
|
+
field_path: matchesAppId ? 'cv_versions_registry.application_ids' : 'cv_versions_registry.tailoring_metadata.target_job_id',
|
|
618
|
+
code: 'third_party_subject',
|
|
619
|
+
reason: 'Application is reverse-linked from a third-party or unverified CV version registry entry.',
|
|
620
|
+
});
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// Unattributed legacy v1 application (neither cv_version_id nor base_cv_version_id set)
|
|
629
|
+
if (!cvId && !baseCvId) {
|
|
630
|
+
if (violations.length === 0) {
|
|
631
|
+
const validReg = allCvRegistry && isObj(allCvRegistry) && validateCvVersionsRegistry(allCvRegistry).valid
|
|
632
|
+
? allCvRegistry
|
|
633
|
+
: null;
|
|
634
|
+
const centralOwn = classifyApplicationOwnership(raw, validReg);
|
|
635
|
+
if (!centralOwn.isOwner) {
|
|
636
|
+
violations.push({
|
|
637
|
+
field_path: 'ownership',
|
|
638
|
+
code: 'third_party_subject',
|
|
639
|
+
reason: `Centralized ownership check blocked record (${centralOwn.reason || 'unverified_ownership'}).`,
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return {
|
|
644
|
+
valid: violations.length === 0,
|
|
645
|
+
attributed: false,
|
|
646
|
+
owner_cv_entry: null,
|
|
647
|
+
violations,
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// Any CV reference requires a valid, unambiguous CV registry
|
|
652
|
+
if (!allCvRegistry || !isObj(allCvRegistry)) {
|
|
653
|
+
violations.push({
|
|
654
|
+
field_path: cvId ? 'cv_version_id' : 'cv_tailoring.base_cv_version_id',
|
|
655
|
+
code: 'third_party_subject',
|
|
656
|
+
reason: 'Referenced CV version cannot be verified because CV version registry is missing.',
|
|
657
|
+
});
|
|
658
|
+
return { valid: false, attributed: true, owner_cv_entry: null, violations };
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const regCheck = validateCvVersionsRegistry(allCvRegistry);
|
|
662
|
+
if (!regCheck.valid) {
|
|
663
|
+
violations.push({
|
|
664
|
+
field_path: 'cv_versions_registry',
|
|
665
|
+
code: 'third_party_subject',
|
|
666
|
+
reason: 'CV version registry failed schema validation; refusing unverified CV attribution.',
|
|
667
|
+
});
|
|
668
|
+
return { valid: false, attributed: true, owner_cv_entry: null, violations };
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
const byId = new Map();
|
|
672
|
+
for (const v of allCvRegistry.versions) {
|
|
673
|
+
if (isObj(v) && isNonEmptyString(v.cv_version_id)) {
|
|
674
|
+
byId.set(v.cv_version_id.trim(), v);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// H1: Recursively verify CV entry AND entire registry base_cv_version_id ancestry chain with cycle detection
|
|
679
|
+
const verifyEntryAndAncestry = (startId, rootFieldPath) => {
|
|
680
|
+
const visited = new Set();
|
|
681
|
+
let currentId = startId;
|
|
682
|
+
let currentPath = rootFieldPath;
|
|
683
|
+
let rootEntry = null;
|
|
684
|
+
|
|
685
|
+
while (currentId !== null) {
|
|
686
|
+
if (visited.has(currentId)) {
|
|
687
|
+
violations.push({
|
|
688
|
+
field_path: currentPath,
|
|
689
|
+
code: 'third_party_subject',
|
|
690
|
+
reason: 'Cyclic base_cv_version_id ancestry detected in CV version registry.',
|
|
691
|
+
});
|
|
692
|
+
return null;
|
|
693
|
+
}
|
|
694
|
+
visited.add(currentId);
|
|
695
|
+
|
|
696
|
+
const entry = byId.get(currentId);
|
|
697
|
+
if (!entry) {
|
|
698
|
+
violations.push({
|
|
699
|
+
field_path: currentPath,
|
|
700
|
+
code: 'third_party_subject',
|
|
701
|
+
reason: 'Referenced CV version or ancestor ID does not exist in owner CV registry.',
|
|
702
|
+
});
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
if (entry.owner_scope !== 'owner') {
|
|
706
|
+
violations.push({
|
|
707
|
+
field_path: currentPath,
|
|
708
|
+
code: 'third_party_subject',
|
|
709
|
+
reason: 'Referenced CV version or ancestor does not explicitly declare owner_scope "owner".',
|
|
710
|
+
});
|
|
711
|
+
return null;
|
|
712
|
+
}
|
|
713
|
+
if (entry.local_ref_rel !== undefined && entry.local_ref_rel !== null) {
|
|
714
|
+
if (isThirdPartyCvPath(entry.local_ref_rel) || isUnsafeRelativeRef(entry.local_ref_rel)) {
|
|
715
|
+
violations.push({
|
|
716
|
+
field_path: `${currentPath}.local_ref_rel`,
|
|
717
|
+
code: 'third_party_subject',
|
|
718
|
+
reason: 'Referenced CV registry entry or ancestor points to a third-party or unsafe path.',
|
|
719
|
+
});
|
|
720
|
+
return null;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
if (rootEntry === null) rootEntry = entry;
|
|
724
|
+
|
|
725
|
+
if (entry.base_cv_version_id === undefined || entry.base_cv_version_id === null || entry.base_cv_version_id === '') {
|
|
726
|
+
currentId = null;
|
|
727
|
+
} else if (typeof entry.base_cv_version_id !== 'string' || entry.base_cv_version_id.trim().length === 0) {
|
|
728
|
+
violations.push({
|
|
729
|
+
field_path: `${currentPath}.base_cv_version_id`,
|
|
730
|
+
code: 'third_party_subject',
|
|
731
|
+
reason: 'Malformed ancestor base_cv_version_id in CV version registry.',
|
|
732
|
+
});
|
|
733
|
+
return null;
|
|
734
|
+
} else {
|
|
735
|
+
currentId = entry.base_cv_version_id.trim();
|
|
736
|
+
currentPath = `${currentPath}.base_cv_version_id`;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
return rootEntry;
|
|
741
|
+
};
|
|
742
|
+
|
|
743
|
+
let primaryEntry = null;
|
|
744
|
+
if (cvId) {
|
|
745
|
+
primaryEntry = verifyEntryAndAncestry(cvId, 'cv_version_id');
|
|
746
|
+
if (primaryEntry && isObj(raw.cv_tailoring) && typeof raw.cv_tailoring.is_tailored === 'boolean') {
|
|
747
|
+
const expectedKind = raw.cv_tailoring.is_tailored ? 'tailored' : 'generic';
|
|
748
|
+
if (primaryEntry.kind !== expectedKind) {
|
|
749
|
+
violations.push({
|
|
750
|
+
field_path: 'cv_tailoring.is_tailored',
|
|
751
|
+
code: 'third_party_subject',
|
|
752
|
+
reason: 'Conflicting CV kind between application cv_tailoring.is_tailored and CV registry entry.',
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
if (baseCvId) {
|
|
759
|
+
const baseEntry = verifyEntryAndAncestry(baseCvId, 'cv_tailoring.base_cv_version_id');
|
|
760
|
+
if (primaryEntry && baseEntry) {
|
|
761
|
+
const regBase = primaryEntry.base_cv_version_id ? primaryEntry.base_cv_version_id.trim() : null;
|
|
762
|
+
if (regBase !== null && regBase !== baseCvId) {
|
|
763
|
+
violations.push({
|
|
764
|
+
field_path: 'cv_tailoring.base_cv_version_id',
|
|
765
|
+
code: 'third_party_subject',
|
|
766
|
+
reason: 'Application base_cv_version_id does not match CV registry base_cv_version_id.',
|
|
767
|
+
});
|
|
768
|
+
} else if (regBase === null && baseCvId !== primaryEntry.cv_version_id.trim()) {
|
|
769
|
+
violations.push({
|
|
770
|
+
field_path: 'cv_tailoring.base_cv_version_id',
|
|
771
|
+
code: 'third_party_subject',
|
|
772
|
+
reason: 'Application declares a base_cv_version_id that contradicts a root CV registry entry.',
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
if (violations.length === 0) {
|
|
779
|
+
const centralOwn = classifyApplicationOwnership(raw, allCvRegistry);
|
|
780
|
+
if (!centralOwn.isOwner) {
|
|
781
|
+
violations.push({
|
|
782
|
+
field_path: 'ownership',
|
|
783
|
+
code: 'third_party_subject',
|
|
784
|
+
reason: `Centralized ownership check blocked record (${centralOwn.reason || 'unverified_ownership'}).`,
|
|
785
|
+
});
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
return {
|
|
790
|
+
valid: violations.length === 0,
|
|
791
|
+
attributed: Boolean(cvId),
|
|
792
|
+
owner_cv_entry: violations.length === 0 ? primaryEntry : null,
|
|
793
|
+
violations,
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
export function checkApplicationSyncEligibility(raw, { allCvRegistry = null } = {}) {
|
|
798
|
+
if (!isObj(raw)) {
|
|
799
|
+
return {
|
|
800
|
+
eligible: false,
|
|
801
|
+
canonical_key: null,
|
|
802
|
+
canonical_status: null,
|
|
803
|
+
block_code: null,
|
|
804
|
+
violations: [],
|
|
805
|
+
reason: 'record_not_object',
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
const keyRes = resolveCanonicalSyncKey('applications', raw);
|
|
810
|
+
const st = normalizeStatus(raw.status);
|
|
811
|
+
const canonicalKey = keyRes.valid ? keyRes.canonical_key : (isNonEmptyString(raw.job_id) ? raw.job_id.trim() : 'unknown');
|
|
812
|
+
|
|
813
|
+
// Check ownership/third-party attribution first so third-party data is ALWAYS blocked, never merely skipped
|
|
814
|
+
const cvAuth = validateCvAttribution(raw, { allCvRegistry });
|
|
815
|
+
if (!cvAuth.valid) {
|
|
816
|
+
return {
|
|
817
|
+
eligible: false,
|
|
818
|
+
canonical_key: canonicalKey,
|
|
819
|
+
canonical_status: st.valid ? st.canonical : null,
|
|
820
|
+
block_code: 'third_party_subject',
|
|
821
|
+
violations: cvAuth.violations,
|
|
822
|
+
reason: 'blocked_cv_or_subject_ownership',
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
if (!keyRes.valid) {
|
|
827
|
+
return {
|
|
828
|
+
eligible: false,
|
|
829
|
+
canonical_key: canonicalKey,
|
|
830
|
+
canonical_status: st.valid ? st.canonical : null,
|
|
831
|
+
block_code: null,
|
|
832
|
+
violations: [],
|
|
833
|
+
reason: keyRes.reason,
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
if (!st.valid) {
|
|
838
|
+
return {
|
|
839
|
+
eligible: false,
|
|
840
|
+
canonical_key: keyRes.canonical_key,
|
|
841
|
+
canonical_status: null,
|
|
842
|
+
block_code: null,
|
|
843
|
+
violations: [],
|
|
844
|
+
reason: 'unrecognized_status',
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
if (!SUBMITTED_STATUS_SET.has(st.canonical)) {
|
|
849
|
+
return {
|
|
850
|
+
eligible: false,
|
|
851
|
+
canonical_key: keyRes.canonical_key,
|
|
852
|
+
canonical_status: st.canonical,
|
|
853
|
+
block_code: null,
|
|
854
|
+
violations: [],
|
|
855
|
+
reason: 'status_not_submitted',
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
if (raw.submission_uncertain === true) {
|
|
860
|
+
return {
|
|
861
|
+
eligible: false,
|
|
862
|
+
canonical_key: keyRes.canonical_key,
|
|
863
|
+
canonical_status: st.canonical,
|
|
864
|
+
block_code: null,
|
|
865
|
+
violations: [],
|
|
866
|
+
reason: 'submission_uncertain',
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
return {
|
|
871
|
+
eligible: true,
|
|
872
|
+
canonical_key: keyRes.canonical_key,
|
|
873
|
+
canonical_status: st.canonical,
|
|
874
|
+
block_code: null,
|
|
875
|
+
violations: [],
|
|
876
|
+
owner_cv_entry: cvAuth.owner_cv_entry,
|
|
877
|
+
reason: null,
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
export function canonicalizeJson(value) {
|
|
882
|
+
if (value === null) return 'null';
|
|
883
|
+
const t = typeof value;
|
|
884
|
+
if (t === 'boolean') return value ? 'true' : 'false';
|
|
885
|
+
if (t === 'number') {
|
|
886
|
+
if (!Number.isFinite(value)) {
|
|
887
|
+
throw new Error('canonicalizeJson cannot serialize non-finite numbers.');
|
|
888
|
+
}
|
|
889
|
+
return JSON.stringify(Object.is(value, -0) ? 0 : value);
|
|
890
|
+
}
|
|
891
|
+
if (t === 'string') return JSON.stringify(value);
|
|
892
|
+
if (Array.isArray(value)) {
|
|
893
|
+
return `[${value.map(item => canonicalizeJson(item === undefined ? null : item)).join(',')}]`;
|
|
894
|
+
}
|
|
895
|
+
if (isObj(value)) {
|
|
896
|
+
const keys = Object.keys(value).sort(codePointCompare);
|
|
897
|
+
const entries = [];
|
|
898
|
+
for (const k of keys) {
|
|
899
|
+
if (value[k] === undefined) continue;
|
|
900
|
+
entries.push(`${JSON.stringify(k)}:${canonicalizeJson(value[k])}`);
|
|
901
|
+
}
|
|
902
|
+
return `{${entries.join(',')}}`;
|
|
903
|
+
}
|
|
904
|
+
throw new Error(`canonicalizeJson received unsupported type "${t}".`);
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
export function computeSyncHash(projectedPayload) {
|
|
908
|
+
if (!isObj(projectedPayload)) {
|
|
909
|
+
throw new Error('computeSyncHash requires a projected payload object.');
|
|
910
|
+
}
|
|
911
|
+
const withoutHash = {};
|
|
912
|
+
for (const [k, v] of Object.entries(projectedPayload)) {
|
|
913
|
+
if (k === 'Sync Hash') continue;
|
|
914
|
+
withoutHash[k] = v;
|
|
915
|
+
}
|
|
916
|
+
return crypto.createHash('sha256').update(canonicalizeJson(withoutHash)).digest('hex').slice(0, 16);
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
export function computeOperationId({ database, canonical_key, action, existing_page_id = null, sync_hash }) {
|
|
920
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
921
|
+
throw new Error(`computeOperationId: invalid database "${database}".`);
|
|
922
|
+
}
|
|
923
|
+
if (!isNonEmptyString(canonical_key)) {
|
|
924
|
+
throw new Error('computeOperationId: canonical_key must be non-empty.');
|
|
925
|
+
}
|
|
926
|
+
if (!OP_ACTIONS.has(action)) {
|
|
927
|
+
throw new Error(`computeOperationId: invalid action "${action}".`);
|
|
928
|
+
}
|
|
929
|
+
if (typeof sync_hash !== 'string' || !HEX16_RE.test(sync_hash)) {
|
|
930
|
+
throw new Error('computeOperationId: sync_hash must be a 16-char lowercase hex string.');
|
|
931
|
+
}
|
|
932
|
+
const normPageId = existing_page_id ? (normalizeNotionUuid(existing_page_id) || String(existing_page_id).trim()) : null;
|
|
933
|
+
const core = {
|
|
934
|
+
database,
|
|
935
|
+
canonical_key: canonical_key.trim(),
|
|
936
|
+
action,
|
|
937
|
+
existing_page_id: normPageId,
|
|
938
|
+
sync_hash,
|
|
939
|
+
};
|
|
940
|
+
return crypto.createHash('sha256').update(canonicalizeJson(core)).digest('hex').slice(0, 16);
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// Non-circular immutable plan_core hash covering ALL operations (including skip_unchanged),
|
|
944
|
+
// blocked_items, skipped_ineligible, and guardrail snapshots; explicitly excludes plan_hash,
|
|
945
|
+
// mode, approval, and per-operation status.
|
|
946
|
+
export function computePlanHash(plan) {
|
|
947
|
+
if (!isObj(plan)) {
|
|
948
|
+
throw new Error('computePlanHash requires a sync plan object.');
|
|
949
|
+
}
|
|
950
|
+
const ops = Array.isArray(plan.operations) ? plan.operations : [];
|
|
951
|
+
const blocked = Array.isArray(plan.blocked_items) ? plan.blocked_items : [];
|
|
952
|
+
const skipped = Array.isArray(plan.skipped_ineligible) ? plan.skipped_ineligible : [];
|
|
953
|
+
|
|
954
|
+
const sortedOps = ops.map(op => ({
|
|
955
|
+
operation_id: op?.operation_id ?? null,
|
|
956
|
+
database: op?.database ?? null,
|
|
957
|
+
canonical_key: op?.canonical_key ?? null,
|
|
958
|
+
application_status: op?.database === 'applications' ? (op?.application_status ?? null) : null,
|
|
959
|
+
action: op?.action ?? null,
|
|
960
|
+
existing_page_id: op?.existing_page_id ?? null,
|
|
961
|
+
sync_hash: op?.sync_hash ?? null,
|
|
962
|
+
payload: isObj(op?.payload) ? op.payload : {},
|
|
963
|
+
})).sort((a, b) =>
|
|
964
|
+
codePointCompare(String(a.database || ''), String(b.database || '')) ||
|
|
965
|
+
codePointCompare(String(a.canonical_key || ''), String(b.canonical_key || '')) ||
|
|
966
|
+
codePointCompare(String(a.operation_id || ''), String(b.operation_id || '')),
|
|
967
|
+
);
|
|
968
|
+
|
|
969
|
+
const sortedBlocked = blocked.map(item => ({
|
|
970
|
+
database: item?.database ?? null,
|
|
971
|
+
canonical_key: item?.canonical_key ?? null,
|
|
972
|
+
state: item?.state ?? null,
|
|
973
|
+
violations: Array.isArray(item?.violations)
|
|
974
|
+
? item.violations.map(v => ({
|
|
975
|
+
field_path: v?.field_path ?? null,
|
|
976
|
+
code: v?.code ?? null,
|
|
977
|
+
reason: v?.reason ?? null,
|
|
978
|
+
})).sort((a, b) =>
|
|
979
|
+
codePointCompare(String(a.field_path || ''), String(b.field_path || '')) ||
|
|
980
|
+
codePointCompare(String(a.code || ''), String(b.code || '')),
|
|
981
|
+
)
|
|
982
|
+
: [],
|
|
983
|
+
})).sort((a, b) =>
|
|
984
|
+
codePointCompare(String(a.database || ''), String(b.database || '')) ||
|
|
985
|
+
codePointCompare(String(a.canonical_key || ''), String(b.canonical_key || '')),
|
|
986
|
+
);
|
|
987
|
+
|
|
988
|
+
const sortedSkipped = skipped.map(item => ({
|
|
989
|
+
canonical_key: item?.canonical_key ?? null,
|
|
990
|
+
status: item?.status ?? null,
|
|
991
|
+
reason: item?.reason ?? null,
|
|
992
|
+
})).sort((a, b) =>
|
|
993
|
+
codePointCompare(String(a.canonical_key || ''), String(b.canonical_key || '')) ||
|
|
994
|
+
codePointCompare(String(a.status || ''), String(b.status || '')) ||
|
|
995
|
+
codePointCompare(String(a.reason || ''), String(b.reason || '')),
|
|
996
|
+
);
|
|
997
|
+
|
|
998
|
+
const planCore = {
|
|
999
|
+
schema_version: plan.schema_version ?? null,
|
|
1000
|
+
plan_id: plan.plan_id ?? null,
|
|
1001
|
+
created_at: plan.created_at ?? null,
|
|
1002
|
+
eligibility_policy: plan.eligibility_policy ?? null,
|
|
1003
|
+
transport_enabled: Boolean(plan.transport_enabled),
|
|
1004
|
+
dry_run: Boolean(plan.dry_run),
|
|
1005
|
+
operations: sortedOps,
|
|
1006
|
+
blocked_items: sortedBlocked,
|
|
1007
|
+
skipped_ineligible: sortedSkipped,
|
|
1008
|
+
};
|
|
1009
|
+
|
|
1010
|
+
return crypto.createHash('sha256').update(canonicalizeJson(planCore)).digest('hex');
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
function projectSafePublicUrl(rawUrl) {
|
|
1014
|
+
if (rawUrl === null || rawUrl === undefined || rawUrl === '') return null;
|
|
1015
|
+
if (typeof rawUrl !== 'string') return null;
|
|
1016
|
+
const trimmed = rawUrl.trim();
|
|
1017
|
+
if (!trimmed) return null;
|
|
1018
|
+
try {
|
|
1019
|
+
const parsed = new URL(trimmed);
|
|
1020
|
+
if (isBlockedSsrfUrl(parsed) !== null) return null;
|
|
1021
|
+
return parsed.href;
|
|
1022
|
+
} catch {
|
|
1023
|
+
return null;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
export function projectApplicationForNotion(raw, { allCvRegistry = null } = {}) {
|
|
1028
|
+
const elig = checkApplicationSyncEligibility(raw, { allCvRegistry });
|
|
1029
|
+
if (!elig.eligible) {
|
|
1030
|
+
throw new Error(`Cannot project ineligible or blocked application (${elig.reason}).`);
|
|
1031
|
+
}
|
|
1032
|
+
|
|
1033
|
+
const role = normalizeString(raw.title) || normalizeString(raw.role);
|
|
1034
|
+
const company = normalizeString(raw.company);
|
|
1035
|
+
const appliedDate = normalizeDateYmd(raw.applied_at || raw.date);
|
|
1036
|
+
const lastUpdated = normalizeDateYmd(raw.updated_at || raw.applied_at || raw.date);
|
|
1037
|
+
const rawScore = raw.match_score !== null && raw.match_score !== undefined ? raw.match_score : raw.score;
|
|
1038
|
+
const cvEntry = elig.owner_cv_entry || null;
|
|
1039
|
+
const cvVersionDisplay = cvEntry
|
|
1040
|
+
? normalizeString(cvEntry.label || cvEntry.cv_version_id)
|
|
1041
|
+
: null;
|
|
1042
|
+
const isTailored = isObj(raw.cv_tailoring) && typeof raw.cv_tailoring.is_tailored === 'boolean'
|
|
1043
|
+
? raw.cv_tailoring.is_tailored
|
|
1044
|
+
: (cvEntry ? cvEntry.kind === 'tailored' : false);
|
|
1045
|
+
|
|
1046
|
+
const payload = {
|
|
1047
|
+
Title: formatNotionApplicationTitle(role, company, elig.canonical_key),
|
|
1048
|
+
'Application ID': elig.canonical_key,
|
|
1049
|
+
'Job ID': normalizeString(raw.job_id),
|
|
1050
|
+
Company: company,
|
|
1051
|
+
Role: role,
|
|
1052
|
+
Status: elig.canonical_status,
|
|
1053
|
+
Platform: (normalizeString(raw.platform) || 'other').toLowerCase(),
|
|
1054
|
+
'Source Channel': classifySourceChannel(raw),
|
|
1055
|
+
'Applied Date': appliedDate,
|
|
1056
|
+
'Last Updated': lastUpdated,
|
|
1057
|
+
'Match Score': normalizeBoundedScore(rawScore),
|
|
1058
|
+
'Job URL': projectSafePublicUrl(raw.url),
|
|
1059
|
+
'CV Version': cvVersionDisplay,
|
|
1060
|
+
Tailored: Boolean(isTailored),
|
|
1061
|
+
'Interview Rounds': Array.isArray(raw.interviews) ? raw.interviews.length : 0,
|
|
1062
|
+
Assessments: Array.isArray(raw.assessments) ? raw.assessments.length : 0,
|
|
1063
|
+
};
|
|
1064
|
+
payload['Sync Hash'] = computeSyncHash(payload);
|
|
1065
|
+
return payload;
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
export function projectDailyRunForNotion(runDoc) {
|
|
1069
|
+
const check = validateDailyRun(runDoc);
|
|
1070
|
+
if (!check.valid) {
|
|
1071
|
+
throw new Error(`Cannot project invalid daily run: ${check.errors.join('; ')}`);
|
|
1072
|
+
}
|
|
1073
|
+
if (runDoc.status !== 'completed' && runDoc.status !== 'aborted') {
|
|
1074
|
+
throw new Error(`Cannot project non-terminal daily run status "${runDoc.status}" (must be completed or aborted).`);
|
|
1075
|
+
}
|
|
1076
|
+
const counts = isObj(runDoc.counts) ? runDoc.counts : {};
|
|
1077
|
+
const payload = {
|
|
1078
|
+
'Run ID': runDoc.run_id.trim(),
|
|
1079
|
+
Status: runDoc.status,
|
|
1080
|
+
'Dry Run': Boolean(runDoc.dry_run),
|
|
1081
|
+
Scanned: normalizeNonNegInt(counts.scanned),
|
|
1082
|
+
Prepared: normalizeNonNegInt(counts.prepared ?? 0),
|
|
1083
|
+
Applied: normalizeNonNegInt(counts.applied),
|
|
1084
|
+
Skipped: normalizeNonNegInt(counts.skipped),
|
|
1085
|
+
'Needs Review': normalizeNonNegInt(counts.needs_review),
|
|
1086
|
+
Failed: normalizeNonNegInt(counts.failed),
|
|
1087
|
+
Platforms: normalizeStringList(runDoc.platforms, { lowercase: true }),
|
|
1088
|
+
};
|
|
1089
|
+
payload['Sync Hash'] = computeSyncHash(payload);
|
|
1090
|
+
return payload;
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
export function projectInsightForNotion(insightDoc) {
|
|
1094
|
+
const check = validateCareerInsights(insightDoc);
|
|
1095
|
+
if (!check.valid) {
|
|
1096
|
+
throw new Error(`Cannot project invalid career insight artifact: ${check.errors.join('; ')}`);
|
|
1097
|
+
}
|
|
1098
|
+
const keyRes = resolveCanonicalSyncKey('insights', insightDoc);
|
|
1099
|
+
if (!keyRes.valid) {
|
|
1100
|
+
throw new Error(`Cannot project insight without valid canonical key (${keyRes.reason}).`);
|
|
1101
|
+
}
|
|
1102
|
+
const topSkills = Array.isArray(insightDoc.top_skills)
|
|
1103
|
+
? normalizeStringList(insightDoc.top_skills.map(s => s?.skill), { limit: 10 })
|
|
1104
|
+
: [];
|
|
1105
|
+
const skillGaps = Array.isArray(insightDoc.skill_gaps)
|
|
1106
|
+
? normalizeStringList(insightDoc.skill_gaps.map(s => s?.skill), { limit: 10 })
|
|
1107
|
+
: [];
|
|
1108
|
+
const sampleSufficient = Boolean(insightDoc.intelligence?.sample_sufficiency?.sufficient);
|
|
1109
|
+
|
|
1110
|
+
const payload = {
|
|
1111
|
+
'Period Key': keyRes.canonical_key,
|
|
1112
|
+
'Report Type': insightDoc.type,
|
|
1113
|
+
Period: insightDoc.period.trim(),
|
|
1114
|
+
'Generated At': normalizeDateIso(insightDoc.generated_at),
|
|
1115
|
+
Submitted: normalizeNonNegInt(insightDoc.applied),
|
|
1116
|
+
Scanned: normalizeNonNegInt(insightDoc.scanned),
|
|
1117
|
+
'Avg Match Score': normalizeBoundedScore(insightDoc.avg_match_score),
|
|
1118
|
+
'Sample Sufficient': sampleSufficient,
|
|
1119
|
+
'Top Skills': topSkills,
|
|
1120
|
+
'Skill Gaps': skillGaps,
|
|
1121
|
+
};
|
|
1122
|
+
payload['Sync Hash'] = computeSyncHash(payload);
|
|
1123
|
+
return payload;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
function scanStringForPrivacyViolations(fieldPath, fieldName, str, violations) {
|
|
1127
|
+
if (typeof str !== 'string' || !str.length) return;
|
|
1128
|
+
|
|
1129
|
+
// 1. Secret tokens
|
|
1130
|
+
if (SECRET_TOKEN_PATTERNS.some(re => re.test(str))) {
|
|
1131
|
+
violations.push({
|
|
1132
|
+
field_path: fieldPath,
|
|
1133
|
+
code: 'secret_token',
|
|
1134
|
+
reason: 'Detected secret token or credential pattern in projected value.',
|
|
1135
|
+
});
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// 2. Private email addresses
|
|
1139
|
+
if (EMAIL_RE.test(str)) {
|
|
1140
|
+
violations.push({
|
|
1141
|
+
field_path: fieldPath,
|
|
1142
|
+
code: 'private_email',
|
|
1143
|
+
reason: 'Detected email address in projected value.',
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
// 3. Phone numbers (skipped on URL, date, ID, and hash fields to prevent false positives)
|
|
1148
|
+
if (!PHONE_SKIP_FIELDS.has(fieldName) && PHONE_PATTERNS.some(re => re.test(str))) {
|
|
1149
|
+
violations.push({
|
|
1150
|
+
field_path: fieldPath,
|
|
1151
|
+
code: 'phone_number',
|
|
1152
|
+
reason: 'Detected phone number pattern in projected value.',
|
|
1153
|
+
});
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
// 4. Local file paths (skip valid public http(s) URLs)
|
|
1157
|
+
const isHttpUrl = /^https?:\/\//i.test(str.trim());
|
|
1158
|
+
if (!isHttpUrl && LOCAL_PATH_PATTERNS.some(re => re.test(str))) {
|
|
1159
|
+
violations.push({
|
|
1160
|
+
field_path: fieldPath,
|
|
1161
|
+
code: 'local_file_path',
|
|
1162
|
+
reason: 'Detected local filesystem path in projected value.',
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
// 5. Raw CV / resume dump
|
|
1167
|
+
const headingMatches = RESUME_HEADING_PATTERNS.filter(re => re.test(str)).length;
|
|
1168
|
+
if (str.length > MAX_PROJECTED_STRING_LEN || RESUME_HTML_RE.test(str) || headingMatches >= 2) {
|
|
1169
|
+
violations.push({
|
|
1170
|
+
field_path: fieldPath,
|
|
1171
|
+
code: 'raw_cv_dump',
|
|
1172
|
+
reason: 'Projected value exceeds safe length or contains raw CV/HTML document content.',
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
// 6. Unsafe URL on URL field
|
|
1177
|
+
if (fieldName === 'Job URL') {
|
|
1178
|
+
try {
|
|
1179
|
+
const parsed = new URL(str.trim());
|
|
1180
|
+
if (isBlockedSsrfUrl(parsed) !== null) {
|
|
1181
|
+
violations.push({
|
|
1182
|
+
field_path: fieldPath,
|
|
1183
|
+
code: 'unsafe_url',
|
|
1184
|
+
reason: 'Projected URL failed SSRF or protocol safety check.',
|
|
1185
|
+
});
|
|
1186
|
+
}
|
|
1187
|
+
} catch {
|
|
1188
|
+
violations.push({
|
|
1189
|
+
field_path: fieldPath,
|
|
1190
|
+
code: 'unsafe_url',
|
|
1191
|
+
reason: 'Projected URL is malformed.',
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
|
|
1197
|
+
// Two-layer fail-closed privacy scanner:
|
|
1198
|
+
// Layer 1 inspects source ownership/CV attribution & URL safety (while ignoring excluded-by-projection fields).
|
|
1199
|
+
// Layer 2 recursively inspects every key and value of the projected Notion payload.
|
|
1200
|
+
export function scanNotionPayloadPrivacy(database, rawRecord, projectedPayload, { allCvRegistry = null } = {}) {
|
|
1201
|
+
const violations = [];
|
|
1202
|
+
|
|
1203
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
1204
|
+
violations.push({
|
|
1205
|
+
field_path: 'database',
|
|
1206
|
+
code: 'eeo_or_sensitive_key',
|
|
1207
|
+
reason: 'Unknown Notion target database rejected fail-closed.',
|
|
1208
|
+
});
|
|
1209
|
+
return { safe: false, violations };
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
// Layer 1: Pre-projection source & CV attribution checks
|
|
1213
|
+
if (database === 'applications') {
|
|
1214
|
+
const cvAuth = validateCvAttribution(rawRecord, { allCvRegistry });
|
|
1215
|
+
if (!cvAuth.valid) {
|
|
1216
|
+
violations.push(...cvAuth.violations);
|
|
1217
|
+
}
|
|
1218
|
+
if (isObj(rawRecord) && rawRecord.url !== undefined && rawRecord.url !== null && rawRecord.url !== '') {
|
|
1219
|
+
if (typeof rawRecord.url !== 'string') {
|
|
1220
|
+
violations.push({
|
|
1221
|
+
field_path: 'source.url',
|
|
1222
|
+
code: 'unsafe_url',
|
|
1223
|
+
reason: 'Source URL is not a valid string.',
|
|
1224
|
+
});
|
|
1225
|
+
} else {
|
|
1226
|
+
const trimmedUrl = rawRecord.url.trim();
|
|
1227
|
+
if (trimmedUrl) {
|
|
1228
|
+
try {
|
|
1229
|
+
const parsed = new URL(trimmedUrl);
|
|
1230
|
+
if (isBlockedSsrfUrl(parsed) !== null) {
|
|
1231
|
+
violations.push({
|
|
1232
|
+
field_path: 'source.url',
|
|
1233
|
+
code: 'unsafe_url',
|
|
1234
|
+
reason: 'Source URL failed SSRF or protocol safety check.',
|
|
1235
|
+
});
|
|
1236
|
+
}
|
|
1237
|
+
} catch {
|
|
1238
|
+
violations.push({
|
|
1239
|
+
field_path: 'source.url',
|
|
1240
|
+
code: 'unsafe_url',
|
|
1241
|
+
reason: 'Source URL is malformed.',
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
} else if (isObj(rawRecord) && rawRecord.provenance?.third_party_subject === true) {
|
|
1248
|
+
violations.push({
|
|
1249
|
+
field_path: 'source.provenance.third_party_subject',
|
|
1250
|
+
code: 'third_party_subject',
|
|
1251
|
+
reason: 'Third-party subject record is excluded from Notion synchronization.',
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
// Layer 2: Post-projection deep allowlist & content inspection
|
|
1256
|
+
if (!isObj(projectedPayload)) {
|
|
1257
|
+
violations.push({
|
|
1258
|
+
field_path: 'payload',
|
|
1259
|
+
code: 'eeo_or_sensitive_key',
|
|
1260
|
+
reason: 'Projected payload must be a JSON object.',
|
|
1261
|
+
});
|
|
1262
|
+
return { safe: false, violations };
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
const allowedSchema = NOTION_DATABASE_SCHEMAS[database];
|
|
1266
|
+
const inspectValue = (val, currentPath, topFieldName) => {
|
|
1267
|
+
if (val === null || val === undefined || typeof val === 'boolean' || typeof val === 'number') {
|
|
1268
|
+
return;
|
|
1269
|
+
}
|
|
1270
|
+
if (typeof val === 'string') {
|
|
1271
|
+
scanStringForPrivacyViolations(currentPath, topFieldName, val, violations);
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
if (Array.isArray(val)) {
|
|
1275
|
+
val.forEach((item, idx) => inspectValue(item, `${currentPath}[${idx}]`, topFieldName));
|
|
1276
|
+
return;
|
|
1277
|
+
}
|
|
1278
|
+
if (isObj(val)) {
|
|
1279
|
+
for (const [k, v] of Object.entries(val)) {
|
|
1280
|
+
if (SENSITIVE_KEY_RE.test(k)) {
|
|
1281
|
+
violations.push({
|
|
1282
|
+
field_path: `${currentPath}.${k}`,
|
|
1283
|
+
code: 'eeo_or_sensitive_key',
|
|
1284
|
+
reason: 'Detected sensitive or EEO key inside projected payload.',
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
inspectValue(v, `${currentPath}.${k}`, topFieldName);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
|
|
1292
|
+
for (const [key, val] of Object.entries(projectedPayload)) {
|
|
1293
|
+
const fieldPath = `payload.${key}`;
|
|
1294
|
+
if (SENSITIVE_KEY_RE.test(key)) {
|
|
1295
|
+
violations.push({
|
|
1296
|
+
field_path: fieldPath,
|
|
1297
|
+
code: 'eeo_or_sensitive_key',
|
|
1298
|
+
reason: 'Detected sensitive or EEO property key in projected payload.',
|
|
1299
|
+
});
|
|
1300
|
+
} else if (!Object.prototype.hasOwnProperty.call(allowedSchema, key)) {
|
|
1301
|
+
violations.push({
|
|
1302
|
+
field_path: fieldPath,
|
|
1303
|
+
code: 'eeo_or_sensitive_key',
|
|
1304
|
+
reason: 'Non-allowlisted property key rejected fail-closed.',
|
|
1305
|
+
});
|
|
1306
|
+
}
|
|
1307
|
+
inspectValue(val, fieldPath, key);
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// Deduplicate identical (field_path, code) violations deterministically
|
|
1311
|
+
const seen = new Set();
|
|
1312
|
+
const deduped = [];
|
|
1313
|
+
for (const v of violations) {
|
|
1314
|
+
const k = `${v.field_path}::${v.code}`;
|
|
1315
|
+
if (seen.has(k)) continue;
|
|
1316
|
+
seen.add(k);
|
|
1317
|
+
deduped.push(v);
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
return { safe: deduped.length === 0, violations: deduped };
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
export function validateNotionSyncPlan(plan) {
|
|
1324
|
+
const errors = [];
|
|
1325
|
+
const warnings = [];
|
|
1326
|
+
|
|
1327
|
+
if (!isObj(plan)) {
|
|
1328
|
+
return { valid: false, errors: ['Sync plan must be a JSON object.'], warnings };
|
|
1329
|
+
}
|
|
1330
|
+
checkAllowedKeys(plan, PLAN_KEYS, 'sync_plan', errors);
|
|
1331
|
+
|
|
1332
|
+
if (plan.schema_version !== '1.0') {
|
|
1333
|
+
errors.push(`sync_plan.schema_version must be "1.0" (got ${JSON.stringify(plan.schema_version)}).`);
|
|
1334
|
+
}
|
|
1335
|
+
if (!isNonEmptyString(plan.plan_id)) errors.push('sync_plan.plan_id must be a non-empty string.');
|
|
1336
|
+
if (typeof plan.plan_hash !== 'string' || !HEX64_RE.test(plan.plan_hash)) {
|
|
1337
|
+
errors.push('sync_plan.plan_hash must be a 64-char lowercase hex SHA-256.');
|
|
1338
|
+
}
|
|
1339
|
+
if (!isValidIsoDateTime(plan.created_at)) errors.push('sync_plan.created_at must be a valid ISO-8601 date-time.');
|
|
1340
|
+
if (!PLAN_MODES.has(plan.mode)) errors.push(`sync_plan.mode "${plan.mode}" is invalid.`);
|
|
1341
|
+
if (plan.eligibility_policy !== 'submitted_only') {
|
|
1342
|
+
errors.push('sync_plan.eligibility_policy must be "submitted_only".');
|
|
1343
|
+
}
|
|
1344
|
+
if (typeof plan.transport_enabled !== 'boolean') errors.push('sync_plan.transport_enabled must be a boolean.');
|
|
1345
|
+
if (typeof plan.dry_run !== 'boolean') errors.push('sync_plan.dry_run must be a boolean.');
|
|
1346
|
+
|
|
1347
|
+
// H2: Execution/verified modes strictly require non-null valid approval metadata
|
|
1348
|
+
if ((plan.mode === 'approved_execute' || plan.mode === 'verified') && (plan.approval === undefined || plan.approval === null)) {
|
|
1349
|
+
errors.push(`sync_plan.approval is required and cannot be null when mode is "${plan.mode}".`);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
if (plan.approval !== undefined && plan.approval !== null) {
|
|
1353
|
+
if (!isObj(plan.approval)) {
|
|
1354
|
+
errors.push('sync_plan.approval must be an object or null.');
|
|
1355
|
+
} else {
|
|
1356
|
+
checkAllowedKeys(plan.approval, APPROVAL_KEYS, 'sync_plan.approval', errors);
|
|
1357
|
+
if (typeof plan.approval.approved_plan_hash !== 'string' || !HEX64_RE.test(plan.approval.approved_plan_hash)) {
|
|
1358
|
+
errors.push('sync_plan.approval.approved_plan_hash must be a 64-char lowercase hex SHA-256.');
|
|
1359
|
+
} else if (typeof plan.plan_hash === 'string' && plan.approval.approved_plan_hash !== plan.plan_hash) {
|
|
1360
|
+
errors.push('sync_plan.approval.approved_plan_hash does not match sync_plan.plan_hash.');
|
|
1361
|
+
}
|
|
1362
|
+
if (!isNonEmptyString(plan.approval.approved_plan_id)) {
|
|
1363
|
+
errors.push('sync_plan.approval.approved_plan_id must be a non-empty string.');
|
|
1364
|
+
} else if (isNonEmptyString(plan.plan_id) && plan.approval.approved_plan_id !== plan.plan_id) {
|
|
1365
|
+
errors.push('sync_plan.approval.approved_plan_id does not match sync_plan.plan_id.');
|
|
1366
|
+
}
|
|
1367
|
+
if (!isValidIsoDateTime(plan.approval.approved_at)) {
|
|
1368
|
+
errors.push('sync_plan.approval.approved_at must be a valid ISO-8601 date-time.');
|
|
1369
|
+
}
|
|
1370
|
+
if (plan.approval.approved_by !== 'owner') {
|
|
1371
|
+
errors.push('sync_plan.approval.approved_by must be "owner".');
|
|
1372
|
+
}
|
|
1373
|
+
if (!Number.isInteger(plan.approval.operation_count) || plan.approval.operation_count < 0) {
|
|
1374
|
+
errors.push('sync_plan.approval.operation_count must be an integer >= 0.');
|
|
1375
|
+
} else if (Array.isArray(plan.operations) && plan.approval.operation_count !== plan.operations.length) {
|
|
1376
|
+
errors.push('sync_plan.approval.operation_count does not match sync_plan.operations.length.');
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
if (!Array.isArray(plan.operations)) {
|
|
1382
|
+
errors.push('sync_plan.operations must be an array.');
|
|
1383
|
+
} else {
|
|
1384
|
+
const seenOpIds = new Set();
|
|
1385
|
+
const seenTargets = new Set();
|
|
1386
|
+
plan.operations.forEach((op, idx) => {
|
|
1387
|
+
const label = `sync_plan.operations[${idx}]`;
|
|
1388
|
+
if (!isObj(op)) {
|
|
1389
|
+
errors.push(`${label} must be an object.`);
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
checkAllowedKeys(op, PLANNED_OP_KEYS, label, errors);
|
|
1393
|
+
const hasValidOpId = typeof op.operation_id === 'string' && HEX16_RE.test(op.operation_id);
|
|
1394
|
+
if (!hasValidOpId) {
|
|
1395
|
+
errors.push(`${label}.operation_id must be a 16-char lowercase hex string.`);
|
|
1396
|
+
} else if (seenOpIds.has(op.operation_id)) {
|
|
1397
|
+
errors.push(`${label}: duplicate operation_id "${op.operation_id}".`);
|
|
1398
|
+
} else {
|
|
1399
|
+
seenOpIds.add(op.operation_id);
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
const hasValidDb = TARGET_DATABASE_SET.has(op.database);
|
|
1403
|
+
const hasValidKey = isNonEmptyString(op.canonical_key);
|
|
1404
|
+
if (!hasValidDb) errors.push(`${label}.database "${op.database}" is invalid.`);
|
|
1405
|
+
if (!hasValidKey) errors.push(`${label}.canonical_key must be a non-empty string.`);
|
|
1406
|
+
if (hasValidDb && hasValidKey) {
|
|
1407
|
+
const targetKey = makeSyncStateKey(op.database, op.canonical_key);
|
|
1408
|
+
if (seenTargets.has(targetKey)) {
|
|
1409
|
+
errors.push(`${label}: duplicate target "${targetKey}" in operations.`);
|
|
1410
|
+
} else {
|
|
1411
|
+
seenTargets.add(targetKey);
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
if (op.database === 'applications') {
|
|
1416
|
+
if (!SUBMITTED_STATUS_SET.has(op.application_status)) {
|
|
1417
|
+
errors.push(`${label}.application_status must be a submitted-only status for applications database.`);
|
|
1418
|
+
}
|
|
1419
|
+
} else if (op.application_status !== undefined && !SUBMITTED_STATUS_SET.has(op.application_status)) {
|
|
1420
|
+
errors.push(`${label}.application_status "${op.application_status}" is not a submitted-only status.`);
|
|
1421
|
+
}
|
|
1422
|
+
const hasValidAction = OP_ACTIONS.has(op.action);
|
|
1423
|
+
if (!hasValidAction) errors.push(`${label}.action "${op.action}" is invalid.`);
|
|
1424
|
+
if (op.existing_page_id !== undefined && op.existing_page_id !== null && typeof op.existing_page_id !== 'string') {
|
|
1425
|
+
errors.push(`${label}.existing_page_id must be a string or null.`);
|
|
1426
|
+
}
|
|
1427
|
+
// R1: Strict action / existing_page_id pairing
|
|
1428
|
+
if (hasValidAction) {
|
|
1429
|
+
if (op.action === 'create') {
|
|
1430
|
+
if (op.existing_page_id !== null && op.existing_page_id !== undefined) {
|
|
1431
|
+
errors.push(`${label}: action "create" requires existing_page_id to be null.`);
|
|
1432
|
+
}
|
|
1433
|
+
} else if (op.action === 'update') {
|
|
1434
|
+
if (!isNonEmptyString(op.existing_page_id) || normalizeNotionUuid(op.existing_page_id) === null) {
|
|
1435
|
+
errors.push(`${label}: action "update" requires a valid Notion UUID existing_page_id.`);
|
|
1436
|
+
}
|
|
1437
|
+
} else if (op.action === 'skip_unchanged') {
|
|
1438
|
+
if (op.existing_page_id !== null && op.existing_page_id !== undefined && normalizeNotionUuid(op.existing_page_id) === null) {
|
|
1439
|
+
errors.push(`${label}: action "skip_unchanged" has invalid Notion UUID existing_page_id.`);
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
const hasValidHash = typeof op.sync_hash === 'string' && HEX16_RE.test(op.sync_hash);
|
|
1444
|
+
if (!hasValidHash) {
|
|
1445
|
+
errors.push(`${label}.sync_hash must be a 16-char lowercase hex string.`);
|
|
1446
|
+
}
|
|
1447
|
+
const hasObjPayload = isObj(op.payload);
|
|
1448
|
+
if (!hasObjPayload) errors.push(`${label}.payload must be an object.`);
|
|
1449
|
+
if (!EXECUTABLE_OP_STATES.has(op.status)) errors.push(`${label}.status "${op.status}" is not an executable operation state.`);
|
|
1450
|
+
|
|
1451
|
+
// H2: Cryptographic & semantic cross-checks on every operation
|
|
1452
|
+
if (hasValidOpId && hasValidDb && hasValidKey && hasValidAction && hasValidHash) {
|
|
1453
|
+
const expectedOpId = computeOperationId({
|
|
1454
|
+
database: op.database,
|
|
1455
|
+
canonical_key: op.canonical_key,
|
|
1456
|
+
action: op.action,
|
|
1457
|
+
existing_page_id: op.existing_page_id ?? null,
|
|
1458
|
+
sync_hash: op.sync_hash,
|
|
1459
|
+
});
|
|
1460
|
+
if (op.operation_id !== expectedOpId) {
|
|
1461
|
+
errors.push(`${label}.operation_id "${op.operation_id}" does not match deterministic ID "${expectedOpId}".`);
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
if (hasObjPayload && hasValidHash) {
|
|
1465
|
+
const expectedSyncHash = computeSyncHash(op.payload);
|
|
1466
|
+
if (op.sync_hash !== expectedSyncHash) {
|
|
1467
|
+
errors.push(`${label}.sync_hash "${op.sync_hash}" does not match computed payload hash "${expectedSyncHash}".`);
|
|
1468
|
+
}
|
|
1469
|
+
if (op.payload['Sync Hash'] !== op.sync_hash) {
|
|
1470
|
+
errors.push(`${label}.payload["Sync Hash"] does not match op.sync_hash.`);
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
// R2: Database-specific canonical key binding across all 3 databases
|
|
1474
|
+
if (hasObjPayload && hasValidDb && hasValidKey) {
|
|
1475
|
+
if (op.database === 'applications') {
|
|
1476
|
+
if (SUBMITTED_STATUS_SET.has(op.application_status) && op.payload.Status !== op.application_status) {
|
|
1477
|
+
errors.push(`${label}.payload.Status "${op.payload.Status}" contradicts application_status "${op.application_status}".`);
|
|
1478
|
+
}
|
|
1479
|
+
if (op.payload['Application ID'] !== op.canonical_key) {
|
|
1480
|
+
errors.push(`${label}.payload["Application ID"] does not match canonical_key "${op.canonical_key}".`);
|
|
1481
|
+
}
|
|
1482
|
+
} else if (op.database === 'daily_runs') {
|
|
1483
|
+
if (op.payload['Run ID'] !== op.canonical_key) {
|
|
1484
|
+
errors.push(`${label}.payload["Run ID"] does not match canonical_key "${op.canonical_key}".`);
|
|
1485
|
+
}
|
|
1486
|
+
} else if (op.database === 'insights') {
|
|
1487
|
+
if (op.payload['Period Key'] !== op.canonical_key) {
|
|
1488
|
+
errors.push(`${label}.payload["Period Key"] does not match canonical_key "${op.canonical_key}".`);
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
if (!Array.isArray(plan.blocked_items)) {
|
|
1496
|
+
errors.push('sync_plan.blocked_items must be an array.');
|
|
1497
|
+
} else {
|
|
1498
|
+
plan.blocked_items.forEach((item, idx) => {
|
|
1499
|
+
const label = `sync_plan.blocked_items[${idx}]`;
|
|
1500
|
+
if (!isObj(item)) {
|
|
1501
|
+
errors.push(`${label} must be an object.`);
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
checkAllowedKeys(item, BLOCKED_ITEM_KEYS, label, errors);
|
|
1505
|
+
if (!TARGET_DATABASE_SET.has(item.database)) errors.push(`${label}.database "${item.database}" is invalid.`);
|
|
1506
|
+
if (!isNonEmptyString(item.canonical_key)) errors.push(`${label}.canonical_key must be a non-empty string.`);
|
|
1507
|
+
if (item.state !== 'blocked_privacy') errors.push(`${label}.state must be "blocked_privacy".`);
|
|
1508
|
+
if (!Array.isArray(item.violations) || item.violations.length === 0) {
|
|
1509
|
+
errors.push(`${label}.violations must be a non-empty array.`);
|
|
1510
|
+
} else {
|
|
1511
|
+
item.violations.forEach((v, vIdx) => {
|
|
1512
|
+
const vLabel = `${label}.violations[${vIdx}]`;
|
|
1513
|
+
if (!isObj(v)) {
|
|
1514
|
+
errors.push(`${vLabel} must be an object.`);
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
checkAllowedKeys(v, PRIVACY_VIOLATION_KEYS, vLabel, errors);
|
|
1518
|
+
if (!isNonEmptyString(v.field_path)) errors.push(`${vLabel}.field_path must be a non-empty string.`);
|
|
1519
|
+
if (!PRIVACY_VIOLATION_CODES.has(v.code)) errors.push(`${vLabel}.code "${v.code}" is invalid.`);
|
|
1520
|
+
if (!isNonEmptyString(v.reason)) errors.push(`${vLabel}.reason must be a non-empty string.`);
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
});
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
if (!Array.isArray(plan.skipped_ineligible)) {
|
|
1527
|
+
errors.push('sync_plan.skipped_ineligible must be an array.');
|
|
1528
|
+
} else {
|
|
1529
|
+
plan.skipped_ineligible.forEach((item, idx) => {
|
|
1530
|
+
const label = `sync_plan.skipped_ineligible[${idx}]`;
|
|
1531
|
+
if (!isObj(item)) {
|
|
1532
|
+
errors.push(`${label} must be an object.`);
|
|
1533
|
+
return;
|
|
1534
|
+
}
|
|
1535
|
+
checkAllowedKeys(item, SKIPPED_INELIGIBLE_KEYS, label, errors);
|
|
1536
|
+
if (!isNonEmptyString(item.canonical_key)) errors.push(`${label}.canonical_key must be a non-empty string.`);
|
|
1537
|
+
if (typeof item.status !== 'string') errors.push(`${label}.status must be a string.`);
|
|
1538
|
+
if (!isNonEmptyString(item.reason)) errors.push(`${label}.reason must be a non-empty string.`);
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
// Recompute plan_hash when structural shape is intact to detect tampering
|
|
1543
|
+
if (errors.length === 0) {
|
|
1544
|
+
const recomputed = computePlanHash(plan);
|
|
1545
|
+
if (recomputed !== plan.plan_hash) {
|
|
1546
|
+
errors.push(`sync_plan.plan_hash mismatch (expected ${recomputed}, got ${plan.plan_hash}); plan may have been tampered with.`);
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
return { valid: errors.length === 0, errors, warnings };
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
export function validateNotionSyncState(stateDoc) {
|
|
1554
|
+
const errors = [];
|
|
1555
|
+
const warnings = [];
|
|
1556
|
+
|
|
1557
|
+
if (!isObj(stateDoc)) {
|
|
1558
|
+
return { valid: false, errors: ['Sync state file must be a JSON object.'], warnings };
|
|
1559
|
+
}
|
|
1560
|
+
checkAllowedKeys(stateDoc, SYNC_STATE_FILE_KEYS, 'sync_state', errors);
|
|
1561
|
+
|
|
1562
|
+
if (stateDoc.schema_version !== '1.0') {
|
|
1563
|
+
errors.push(`sync_state.schema_version must be "1.0" (got ${JSON.stringify(stateDoc.schema_version)}).`);
|
|
1564
|
+
}
|
|
1565
|
+
if (stateDoc.updated_at !== null && !isValidIsoDateTime(stateDoc.updated_at)) {
|
|
1566
|
+
errors.push('sync_state.updated_at must be an ISO-8601 date-time or null.');
|
|
1567
|
+
}
|
|
1568
|
+
if (!isObj(stateDoc.records)) {
|
|
1569
|
+
errors.push('sync_state.records must be an object map.');
|
|
1570
|
+
return { valid: false, errors, warnings };
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
for (const [recKey, entry] of Object.entries(stateDoc.records)) {
|
|
1574
|
+
const label = `sync_state.records["${recKey}"]`;
|
|
1575
|
+
if (!isObj(entry)) {
|
|
1576
|
+
errors.push(`${label} must be an object.`);
|
|
1577
|
+
continue;
|
|
1578
|
+
}
|
|
1579
|
+
checkAllowedKeys(entry, SYNC_STATE_ENTRY_KEYS, label, errors);
|
|
1580
|
+
const hasValidDb = TARGET_DATABASE_SET.has(entry.database);
|
|
1581
|
+
const hasValidKey = isNonEmptyString(entry.canonical_key);
|
|
1582
|
+
if (!hasValidDb) errors.push(`${label}.database "${entry.database}" is invalid.`);
|
|
1583
|
+
if (!hasValidKey) errors.push(`${label}.canonical_key must be a non-empty string.`);
|
|
1584
|
+
// M1: Enforce exact map-key binding against makeSyncStateKey(database, canonical_key)
|
|
1585
|
+
if (hasValidDb && hasValidKey) {
|
|
1586
|
+
const expectedRecKey = makeSyncStateKey(entry.database, entry.canonical_key);
|
|
1587
|
+
if (recKey !== expectedRecKey) {
|
|
1588
|
+
errors.push(`${label}: record key "${recKey}" does not match expected key "${expectedRecKey}".`);
|
|
1589
|
+
}
|
|
1590
|
+
}
|
|
1591
|
+
if (!SYNC_ITEM_STATES.has(entry.state)) errors.push(`${label}.state "${entry.state}" is invalid.`);
|
|
1592
|
+
// M1: Any non-null page_id must be a valid Notion UUID across ALL states
|
|
1593
|
+
if (entry.page_id !== undefined && entry.page_id !== null) {
|
|
1594
|
+
if (typeof entry.page_id !== 'string' || normalizeNotionUuid(entry.page_id) === null) {
|
|
1595
|
+
errors.push(`${label}.page_id must be a valid Notion UUID or null.`);
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
// M1: Enforce 16-hex SHA-256 format on last_synced_hash & attempted_hash
|
|
1599
|
+
for (const hKey of ['last_synced_hash', 'attempted_hash']) {
|
|
1600
|
+
if (entry[hKey] !== undefined && entry[hKey] !== null && (typeof entry[hKey] !== 'string' || !HEX16_RE.test(entry[hKey]))) {
|
|
1601
|
+
errors.push(`${label}.${hKey} must be a 16-char lowercase hex string or null.`);
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
// M1: Enforce required invariants for state === "synced"
|
|
1605
|
+
if (entry.state === 'synced') {
|
|
1606
|
+
if (!isNonEmptyString(entry.page_id) || normalizeNotionUuid(entry.page_id) === null) {
|
|
1607
|
+
errors.push(`${label}: state "synced" requires a valid Notion UUID page_id.`);
|
|
1608
|
+
}
|
|
1609
|
+
if (typeof entry.last_synced_hash !== 'string' || !HEX16_RE.test(entry.last_synced_hash)) {
|
|
1610
|
+
errors.push(`${label}: state "synced" requires a valid 16-char hex last_synced_hash.`);
|
|
1611
|
+
}
|
|
1612
|
+
}
|
|
1613
|
+
// R3 + D5: Enforce validator contract for state === "in_flight" (requires non-null ISO-8601 attempted_at)
|
|
1614
|
+
if (entry.state === 'in_flight') {
|
|
1615
|
+
if (typeof entry.attempted_hash !== 'string' || !HEX16_RE.test(entry.attempted_hash)) {
|
|
1616
|
+
errors.push(`${label}: state "in_flight" requires a valid 16-char hex attempted_hash.`);
|
|
1617
|
+
}
|
|
1618
|
+
if (!isValidIsoDateTime(entry.attempted_at)) {
|
|
1619
|
+
errors.push(`${label}: state "in_flight" requires a valid ISO-8601 date-time attempted_at.`);
|
|
1620
|
+
}
|
|
1621
|
+
if (typeof entry.operation_id !== 'string' || !HEX16_RE.test(entry.operation_id)) {
|
|
1622
|
+
errors.push(`${label}: state "in_flight" requires a valid 16-char hex operation_id.`);
|
|
1623
|
+
}
|
|
1624
|
+
if (typeof entry.approved_plan_hash !== 'string' || !HEX64_RE.test(entry.approved_plan_hash)) {
|
|
1625
|
+
errors.push(`${label}: state "in_flight" requires a valid 64-char hex approved_plan_hash.`);
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
for (const dtKey of ['attempted_at', 'last_synced_at', 'next_retry_after']) {
|
|
1629
|
+
if (entry[dtKey] !== undefined && entry[dtKey] !== null && !isValidIsoDateTime(entry[dtKey])) {
|
|
1630
|
+
errors.push(`${label}.${dtKey} must be a valid ISO-8601 date-time or null.`);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
if (entry.operation_id !== undefined && entry.operation_id !== null && (typeof entry.operation_id !== 'string' || !HEX16_RE.test(entry.operation_id))) {
|
|
1634
|
+
errors.push(`${label}.operation_id must be a 16-char lowercase hex string or null.`);
|
|
1635
|
+
}
|
|
1636
|
+
if (entry.approved_plan_hash !== undefined && entry.approved_plan_hash !== null && (typeof entry.approved_plan_hash !== 'string' || !HEX64_RE.test(entry.approved_plan_hash))) {
|
|
1637
|
+
errors.push(`${label}.approved_plan_hash must be a 64-char lowercase hex SHA-256 or null.`);
|
|
1638
|
+
}
|
|
1639
|
+
if (entry.retry_count !== undefined && (!Number.isInteger(entry.retry_count) || entry.retry_count < 0)) {
|
|
1640
|
+
errors.push(`${label}.retry_count must be an integer >= 0.`);
|
|
1641
|
+
}
|
|
1642
|
+
// M1: Validate conflicting_page_ids as valid Notion UUIDs, and require >= 2 distinct UUIDs for conflict_duplicate_remote
|
|
1643
|
+
if (entry.conflicting_page_ids !== undefined) {
|
|
1644
|
+
if (!Array.isArray(entry.conflicting_page_ids) || entry.conflicting_page_ids.some(id => typeof id !== 'string' || normalizeNotionUuid(id) === null)) {
|
|
1645
|
+
errors.push(`${label}.conflicting_page_ids must be an array of valid Notion UUID strings.`);
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
if (entry.state === 'conflict_duplicate_remote') {
|
|
1649
|
+
const validConflictUuids = Array.isArray(entry.conflicting_page_ids)
|
|
1650
|
+
? new Set(entry.conflicting_page_ids.map(id => normalizeNotionUuid(id)).filter(Boolean))
|
|
1651
|
+
: new Set();
|
|
1652
|
+
if (validConflictUuids.size < 2) {
|
|
1653
|
+
errors.push(`${label}: state "conflict_duplicate_remote" requires at least 2 distinct valid Notion UUIDs in conflicting_page_ids.`);
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
if (entry.last_error !== undefined && entry.last_error !== null && typeof entry.last_error !== 'string') {
|
|
1657
|
+
errors.push(`${label}.last_error must be a string or null.`);
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
return { valid: errors.length === 0, errors, warnings };
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
// ---------------- Stage 3 (T8-A): Sync-State Foundation & Deterministic Diff ----------------
|
|
1665
|
+
|
|
1666
|
+
export function createEmptySyncState(updatedAt = null) {
|
|
1667
|
+
if (updatedAt !== null && !isValidIsoDateTime(updatedAt)) {
|
|
1668
|
+
throw new Error(`Invalid updatedAt timestamp for empty sync state: "${updatedAt}".`);
|
|
1669
|
+
}
|
|
1670
|
+
return {
|
|
1671
|
+
schema_version: '1.0',
|
|
1672
|
+
updated_at: updatedAt,
|
|
1673
|
+
records: {},
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
export function normalizeSyncState(rawState) {
|
|
1678
|
+
const check = verifySyncStateIntegrity(rawState);
|
|
1679
|
+
if (!check.valid) {
|
|
1680
|
+
throw new Error(`Invalid sync-state document: ${check.errors.join('; ')}`);
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
const sortedKeys = Object.keys(rawState.records).sort(codePointCompare);
|
|
1684
|
+
const normalizedRecords = {};
|
|
1685
|
+
for (const key of sortedKeys) {
|
|
1686
|
+
const entry = rawState.records[key];
|
|
1687
|
+
const normEntry = {
|
|
1688
|
+
database: entry.database,
|
|
1689
|
+
canonical_key: entry.canonical_key.trim(),
|
|
1690
|
+
state: entry.state,
|
|
1691
|
+
};
|
|
1692
|
+
if (entry.page_id !== undefined) {
|
|
1693
|
+
if (entry.page_id === null) {
|
|
1694
|
+
normEntry.page_id = null;
|
|
1695
|
+
} else {
|
|
1696
|
+
const normUuid = normalizeNotionUuid(entry.page_id);
|
|
1697
|
+
if (!normUuid) {
|
|
1698
|
+
throw new Error(`sync_state.records["${key}"].page_id is not a valid Notion UUID.`);
|
|
1699
|
+
}
|
|
1700
|
+
normEntry.page_id = normUuid;
|
|
1701
|
+
}
|
|
1702
|
+
}
|
|
1703
|
+
if (entry.last_synced_hash !== undefined) normEntry.last_synced_hash = entry.last_synced_hash;
|
|
1704
|
+
if (entry.attempted_hash !== undefined) normEntry.attempted_hash = entry.attempted_hash;
|
|
1705
|
+
if (entry.attempted_at !== undefined) normEntry.attempted_at = entry.attempted_at;
|
|
1706
|
+
if (entry.last_synced_at !== undefined) normEntry.last_synced_at = entry.last_synced_at;
|
|
1707
|
+
if (entry.operation_id !== undefined) normEntry.operation_id = entry.operation_id;
|
|
1708
|
+
if (entry.approved_plan_hash !== undefined) normEntry.approved_plan_hash = entry.approved_plan_hash;
|
|
1709
|
+
if (entry.retry_count !== undefined) normEntry.retry_count = entry.retry_count;
|
|
1710
|
+
if (entry.next_retry_after !== undefined) normEntry.next_retry_after = entry.next_retry_after;
|
|
1711
|
+
if (entry.conflicting_page_ids !== undefined) {
|
|
1712
|
+
const seenIds = new Set();
|
|
1713
|
+
const normConflicts = [];
|
|
1714
|
+
for (const cid of entry.conflicting_page_ids) {
|
|
1715
|
+
const norm = normalizeNotionUuid(cid);
|
|
1716
|
+
if (!norm) {
|
|
1717
|
+
throw new Error(`sync_state.records["${key}"].conflicting_page_ids contains invalid Notion UUID.`);
|
|
1718
|
+
}
|
|
1719
|
+
if (seenIds.has(norm)) continue;
|
|
1720
|
+
seenIds.add(norm);
|
|
1721
|
+
normConflicts.push(norm);
|
|
1722
|
+
}
|
|
1723
|
+
normEntry.conflicting_page_ids = normConflicts.sort(codePointCompare);
|
|
1724
|
+
}
|
|
1725
|
+
if (entry.last_error !== undefined) normEntry.last_error = entry.last_error;
|
|
1726
|
+
|
|
1727
|
+
normalizedRecords[key] = normEntry;
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
return {
|
|
1731
|
+
schema_version: '1.0',
|
|
1732
|
+
updated_at: rawState.updated_at,
|
|
1733
|
+
records: normalizedRecords,
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
|
|
1737
|
+
export function loadSyncState(root, { home = os.homedir() } = {}) {
|
|
1738
|
+
if (!isNonEmptyString(root)) {
|
|
1739
|
+
throw new Error('loadSyncState requires a non-empty workspace root path.');
|
|
1740
|
+
}
|
|
1741
|
+
const statePath = path.join(root, 'logs', 'sync-state.json');
|
|
1742
|
+
// Unconditional symlink check catches both live and dangling symlinks before read
|
|
1743
|
+
refuseSymlink(statePath, root, home);
|
|
1744
|
+
if (!fs.existsSync(statePath)) {
|
|
1745
|
+
return { exists: false, path: statePath, state: createEmptySyncState(null) };
|
|
1746
|
+
}
|
|
1747
|
+
let parsed;
|
|
1748
|
+
try {
|
|
1749
|
+
parsed = JSON.parse(fs.readFileSync(statePath, 'utf8'));
|
|
1750
|
+
} catch (err) {
|
|
1751
|
+
throw new Error(`Invalid JSON in ${statePath}: ${err.message}`);
|
|
1752
|
+
}
|
|
1753
|
+
const normalized = normalizeSyncState(parsed);
|
|
1754
|
+
return { exists: true, path: statePath, state: normalized };
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
export function saveSyncState(root, stateDoc, { home = os.homedir(), nowIso = new Date().toISOString() } = {}) {
|
|
1758
|
+
if (!isNonEmptyString(root)) {
|
|
1759
|
+
throw new Error('saveSyncState requires a non-empty workspace root path.');
|
|
1760
|
+
}
|
|
1761
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
1762
|
+
throw new Error(`Invalid nowIso timestamp: "${nowIso}".`);
|
|
1763
|
+
}
|
|
1764
|
+
const statePath = path.join(root, 'logs', 'sync-state.json');
|
|
1765
|
+
refuseSymlink(statePath, root, home);
|
|
1766
|
+
const normalized = normalizeSyncState({
|
|
1767
|
+
...stateDoc,
|
|
1768
|
+
updated_at: nowIso,
|
|
1769
|
+
});
|
|
1770
|
+
writeAtomic(statePath, JSON.stringify(normalized, null, 2) + '\n', {
|
|
1771
|
+
mode: 0o600,
|
|
1772
|
+
boundary: root,
|
|
1773
|
+
home,
|
|
1774
|
+
});
|
|
1775
|
+
const reread = JSON.parse(fs.readFileSync(statePath, 'utf8'));
|
|
1776
|
+
const postCheck = validateNotionSyncState(reread);
|
|
1777
|
+
if (!postCheck.valid) {
|
|
1778
|
+
throw new Error(`Post-write sync-state validation failed: ${postCheck.errors.join('; ')}`);
|
|
1779
|
+
}
|
|
1780
|
+
return { path: statePath, state: normalized };
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
function validateRemoteIndexKey(stateKey) {
|
|
1784
|
+
if (typeof stateKey !== 'string') return false;
|
|
1785
|
+
const parts = stateKey.split('::');
|
|
1786
|
+
if (parts.length !== 2) return false;
|
|
1787
|
+
const [database, canonicalKey] = parts;
|
|
1788
|
+
if (!TARGET_DATABASE_SET.has(database)) return false;
|
|
1789
|
+
if (!canonicalKey || canonicalKey !== canonicalKey.trim()) return false;
|
|
1790
|
+
if (database === 'applications') return APP_ID_RE.test(canonicalKey);
|
|
1791
|
+
if (database === 'daily_runs') return RUN_ID_RE.test(canonicalKey);
|
|
1792
|
+
if (database === 'insights') {
|
|
1793
|
+
const colonIdx = canonicalKey.indexOf(':');
|
|
1794
|
+
if (colonIdx <= 0) return false;
|
|
1795
|
+
const type = canonicalKey.slice(0, colonIdx);
|
|
1796
|
+
const period = canonicalKey.slice(colonIdx + 1);
|
|
1797
|
+
return ALLOWED_INSIGHT_TYPES.has(type) && period.trim().length > 0 && period === period.trim();
|
|
1798
|
+
}
|
|
1799
|
+
return false;
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
function normalizeRemoteIndex(remoteIndex) {
|
|
1803
|
+
if (remoteIndex === null || remoteIndex === undefined) return null;
|
|
1804
|
+
if (!isObj(remoteIndex)) {
|
|
1805
|
+
throw new Error('remoteIndex must be an object mapping "${database}::${canonical_key}" to remote page arrays, or null.');
|
|
1806
|
+
}
|
|
1807
|
+
const normalized = new Map();
|
|
1808
|
+
// R6: Track normalized active page_id ownership across ALL canonical remote keys
|
|
1809
|
+
const globalPageOwners = new Map();
|
|
1810
|
+
const sortedEntries = Object.entries(remoteIndex).sort((a, b) => codePointCompare(a[0], b[0]));
|
|
1811
|
+
for (const [stateKey, pages] of sortedEntries) {
|
|
1812
|
+
// M2: Fail closed on malformed remoteIndex keys
|
|
1813
|
+
if (!validateRemoteIndexKey(stateKey)) {
|
|
1814
|
+
throw new Error(`Malformed remoteIndex key "${stateKey}"; expected "<database>::<canonical_key>" with valid database and key format.`);
|
|
1815
|
+
}
|
|
1816
|
+
if (!Array.isArray(pages)) {
|
|
1817
|
+
throw new Error(`remoteIndex["${stateKey}"] must be an array of remote page descriptors.`);
|
|
1818
|
+
}
|
|
1819
|
+
const cleanPages = [];
|
|
1820
|
+
const seenPages = new Map();
|
|
1821
|
+
for (let i = 0; i < pages.length; i++) {
|
|
1822
|
+
const p = pages[i];
|
|
1823
|
+
if (!isObj(p)) {
|
|
1824
|
+
throw new Error(`remoteIndex["${stateKey}"][${i}] must be an object.`);
|
|
1825
|
+
}
|
|
1826
|
+
if (p.archived === true || p.in_trash === true) continue;
|
|
1827
|
+
const normId = normalizeNotionUuid(p.page_id ?? p.id);
|
|
1828
|
+
if (!normId) {
|
|
1829
|
+
throw new Error(`remoteIndex["${stateKey}"][${i}] has invalid or missing Notion UUID page_id.`);
|
|
1830
|
+
}
|
|
1831
|
+
if (p.sync_hash !== undefined && p.sync_hash !== null && (typeof p.sync_hash !== 'string' || !HEX16_RE.test(p.sync_hash))) {
|
|
1832
|
+
throw new Error(`remoteIndex["${stateKey}"][${i}].sync_hash must be a 16-char lowercase hex string or null.`);
|
|
1833
|
+
}
|
|
1834
|
+
const prevOwner = globalPageOwners.get(normId);
|
|
1835
|
+
if (prevOwner !== undefined && prevOwner !== stateKey) {
|
|
1836
|
+
throw new Error(`Duplicate remote page_id "${normId}" mapped to multiple canonical keys ("${prevOwner}" and "${stateKey}"); refusing ambiguous sync diff.`);
|
|
1837
|
+
}
|
|
1838
|
+
globalPageOwners.set(normId, stateKey);
|
|
1839
|
+
const nextHash = p.sync_hash ?? null;
|
|
1840
|
+
// H1: Deduplicate identical (page_id, sync_hash) pairs; fail closed on conflicting hashes for same page_id
|
|
1841
|
+
if (seenPages.has(normId)) {
|
|
1842
|
+
if (seenPages.get(normId) !== nextHash) {
|
|
1843
|
+
throw new Error(`Conflicting sync_hash values for duplicate remote page_id "${normId}" under "${stateKey}".`);
|
|
1844
|
+
}
|
|
1845
|
+
continue;
|
|
1846
|
+
}
|
|
1847
|
+
seenPages.set(normId, nextHash);
|
|
1848
|
+
cleanPages.push({
|
|
1849
|
+
page_id: normId,
|
|
1850
|
+
sync_hash: nextHash,
|
|
1851
|
+
});
|
|
1852
|
+
}
|
|
1853
|
+
cleanPages.sort((a, b) => codePointCompare(a.page_id, b.page_id));
|
|
1854
|
+
normalized.set(stateKey, cleanPages);
|
|
1855
|
+
}
|
|
1856
|
+
return normalized;
|
|
1857
|
+
}
|
|
1858
|
+
|
|
1859
|
+
const HELD_LOCAL_STATES = new Set([
|
|
1860
|
+
'in_flight',
|
|
1861
|
+
'receipt_uncertain',
|
|
1862
|
+
'failed_retryable',
|
|
1863
|
+
'failed_permanent',
|
|
1864
|
+
'conflict_duplicate_remote',
|
|
1865
|
+
]);
|
|
1866
|
+
|
|
1867
|
+
// Pure deterministic operation diff generator (T8-A).
|
|
1868
|
+
// Never mutates input records, never writes files, never executes transport/approval/receipts/retries.
|
|
1869
|
+
export function computeNotionSyncDiff({
|
|
1870
|
+
applications = [],
|
|
1871
|
+
dailyRuns = [],
|
|
1872
|
+
insights = [],
|
|
1873
|
+
allCvRegistry = null,
|
|
1874
|
+
syncState = null,
|
|
1875
|
+
remoteIndex = null,
|
|
1876
|
+
planId = null,
|
|
1877
|
+
createdAt = new Date().toISOString(),
|
|
1878
|
+
transportEnabled = false,
|
|
1879
|
+
dryRun = true,
|
|
1880
|
+
} = {}) {
|
|
1881
|
+
if (!Array.isArray(applications)) throw new Error('computeNotionSyncDiff: applications must be an array.');
|
|
1882
|
+
if (!Array.isArray(dailyRuns)) throw new Error('computeNotionSyncDiff: dailyRuns must be an array.');
|
|
1883
|
+
if (!Array.isArray(insights)) throw new Error('computeNotionSyncDiff: insights must be an array.');
|
|
1884
|
+
if (!isValidIsoDateTime(createdAt)) throw new Error(`computeNotionSyncDiff: invalid createdAt "${createdAt}".`);
|
|
1885
|
+
|
|
1886
|
+
const normalizedState = syncState === null ? createEmptySyncState(null) : normalizeSyncState(syncState);
|
|
1887
|
+
const normalizedRemote = normalizeRemoteIndex(remoteIndex);
|
|
1888
|
+
|
|
1889
|
+
const operations = [];
|
|
1890
|
+
const blockedItems = [];
|
|
1891
|
+
const skippedIneligible = [];
|
|
1892
|
+
const heldItems = [];
|
|
1893
|
+
|
|
1894
|
+
const seenLocalKeys = new Set();
|
|
1895
|
+
const claimLocalKey = (database, canonicalKey) => {
|
|
1896
|
+
const stateKey = makeSyncStateKey(database, canonicalKey);
|
|
1897
|
+
if (seenLocalKeys.has(stateKey)) {
|
|
1898
|
+
throw new Error(`Duplicate local canonical key "${stateKey}" detected; refusing ambiguous sync diff.`);
|
|
1899
|
+
}
|
|
1900
|
+
seenLocalKeys.add(stateKey);
|
|
1901
|
+
return stateKey;
|
|
1902
|
+
};
|
|
1903
|
+
|
|
1904
|
+
const resolveDiffAction = ({ database, canonicalKey, applicationStatus = null, payload }) => {
|
|
1905
|
+
const stateKey = makeSyncStateKey(database, canonicalKey);
|
|
1906
|
+
const entry = normalizedState.records[stateKey] || null;
|
|
1907
|
+
const hasRemoteEntry = normalizedRemote !== null && normalizedRemote.has(stateKey);
|
|
1908
|
+
const remotePages = hasRemoteEntry ? normalizedRemote.get(stateKey) : null;
|
|
1909
|
+
const syncHash = payload['Sync Hash'];
|
|
1910
|
+
|
|
1911
|
+
// 1. Remote duplicate conflict always holds fail-closed
|
|
1912
|
+
if (remotePages !== null && remotePages.length > 1) {
|
|
1913
|
+
heldItems.push({
|
|
1914
|
+
database,
|
|
1915
|
+
canonical_key: canonicalKey,
|
|
1916
|
+
state: 'conflict_duplicate_remote',
|
|
1917
|
+
reason: 'duplicate_remote_pages',
|
|
1918
|
+
conflicting_page_ids: remotePages.map(p => p.page_id),
|
|
1919
|
+
});
|
|
1920
|
+
return;
|
|
1921
|
+
}
|
|
1922
|
+
|
|
1923
|
+
// 2. Local uncertain / in-flight / conflict / failed states never auto-create or bypass in T8-A
|
|
1924
|
+
if (entry !== null && HELD_LOCAL_STATES.has(entry.state)) {
|
|
1925
|
+
heldItems.push({
|
|
1926
|
+
database,
|
|
1927
|
+
canonical_key: canonicalKey,
|
|
1928
|
+
state: entry.state,
|
|
1929
|
+
reason: entry.state === 'conflict_duplicate_remote'
|
|
1930
|
+
? 'duplicate_remote_pages'
|
|
1931
|
+
: 'requires_reconciliation_or_recovery',
|
|
1932
|
+
conflicting_page_ids: entry.conflicting_page_ids ? [...entry.conflicting_page_ids] : [],
|
|
1933
|
+
});
|
|
1934
|
+
return;
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
const localPageId = entry?.page_id ?? null;
|
|
1938
|
+
const remoteSingle = remotePages !== null && remotePages.length === 1 ? remotePages[0] : null;
|
|
1939
|
+
|
|
1940
|
+
// 3. Contradictory / stale remote state checks (never blindly create or update missing remote pages!)
|
|
1941
|
+
// L1: Hold ANY entry with non-null localPageId when remote explicitly reports 0 matching pages
|
|
1942
|
+
if (localPageId !== null && hasRemoteEntry && remotePages.length === 0) {
|
|
1943
|
+
heldItems.push({
|
|
1944
|
+
database,
|
|
1945
|
+
canonical_key: canonicalKey,
|
|
1946
|
+
state: 'receipt_uncertain',
|
|
1947
|
+
reason: entry?.state === 'synced' ? 'synced_page_missing_remotely' : 'local_page_missing_remotely',
|
|
1948
|
+
conflicting_page_ids: [],
|
|
1949
|
+
});
|
|
1950
|
+
return;
|
|
1951
|
+
}
|
|
1952
|
+
if (localPageId !== null && remoteSingle !== null && localPageId !== remoteSingle.page_id) {
|
|
1953
|
+
heldItems.push({
|
|
1954
|
+
database,
|
|
1955
|
+
canonical_key: canonicalKey,
|
|
1956
|
+
state: 'receipt_uncertain',
|
|
1957
|
+
reason: 'local_remote_page_id_mismatch',
|
|
1958
|
+
conflicting_page_ids: [localPageId, remoteSingle.page_id].sort(codePointCompare),
|
|
1959
|
+
});
|
|
1960
|
+
return;
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
const resolvedPageId = localPageId || remoteSingle?.page_id || null;
|
|
1964
|
+
const knownRemoteHash = remoteSingle !== null && remoteSingle.sync_hash !== null
|
|
1965
|
+
? remoteSingle.sync_hash
|
|
1966
|
+
: (entry?.state === 'synced' ? entry.last_synced_hash : null);
|
|
1967
|
+
|
|
1968
|
+
let action;
|
|
1969
|
+
if (resolvedPageId !== null) {
|
|
1970
|
+
action = knownRemoteHash === syncHash ? 'skip_unchanged' : 'update';
|
|
1971
|
+
} else {
|
|
1972
|
+
action = 'create';
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
const op = {
|
|
1976
|
+
operation_id: computeOperationId({
|
|
1977
|
+
database,
|
|
1978
|
+
canonical_key: canonicalKey,
|
|
1979
|
+
action,
|
|
1980
|
+
existing_page_id: resolvedPageId,
|
|
1981
|
+
sync_hash: syncHash,
|
|
1982
|
+
}),
|
|
1983
|
+
database,
|
|
1984
|
+
canonical_key: canonicalKey,
|
|
1985
|
+
...(database === 'applications' ? { application_status: applicationStatus } : {}),
|
|
1986
|
+
action,
|
|
1987
|
+
existing_page_id: resolvedPageId,
|
|
1988
|
+
sync_hash: syncHash,
|
|
1989
|
+
payload,
|
|
1990
|
+
status: 'previewed',
|
|
1991
|
+
};
|
|
1992
|
+
operations.push(op);
|
|
1993
|
+
};
|
|
1994
|
+
|
|
1995
|
+
// H2: Detect duplicate usable local canonical keys across ALL records BEFORE eligibility filtering
|
|
1996
|
+
for (const raw of applications) {
|
|
1997
|
+
if (isObj(raw) && isUsableJobId(raw.job_id)) {
|
|
1998
|
+
claimLocalKey('applications', computeApplicationId(raw.job_id));
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
for (const runDoc of dailyRuns) {
|
|
2002
|
+
const keyRes = resolveCanonicalSyncKey('daily_runs', runDoc);
|
|
2003
|
+
if (keyRes.valid) claimLocalKey('daily_runs', keyRes.canonical_key);
|
|
2004
|
+
}
|
|
2005
|
+
for (const insightDoc of insights) {
|
|
2006
|
+
const keyRes = resolveCanonicalSyncKey('insights', insightDoc);
|
|
2007
|
+
if (keyRes.valid) claimLocalKey('insights', keyRes.canonical_key);
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
// M3 + R4: Deterministic, PII-free, cycle/BigInt-safe, order-independent diagnostic key for missing-ID third-party records
|
|
2011
|
+
const safeCanonicalizeForHash = (value, seen = new WeakSet()) => {
|
|
2012
|
+
if (value === null) return 'null';
|
|
2013
|
+
const t = typeof value;
|
|
2014
|
+
if (t === 'undefined') return '"[undefined]"';
|
|
2015
|
+
if (t === 'boolean') return value ? 'true' : 'false';
|
|
2016
|
+
if (t === 'number') {
|
|
2017
|
+
return Number.isFinite(value)
|
|
2018
|
+
? JSON.stringify(Object.is(value, -0) ? 0 : value)
|
|
2019
|
+
: JSON.stringify(`[number:${String(value)}]`);
|
|
2020
|
+
}
|
|
2021
|
+
if (t === 'bigint') return JSON.stringify(`[bigint:${value.toString()}]`);
|
|
2022
|
+
if (t === 'string') return JSON.stringify(value);
|
|
2023
|
+
if (t === 'symbol') return JSON.stringify(`[symbol:${String(value.description ?? '')}]`);
|
|
2024
|
+
if (t === 'function') return '"[function]"';
|
|
2025
|
+
if (typeof value === 'object') {
|
|
2026
|
+
if (seen.has(value)) return '"[circular]"';
|
|
2027
|
+
seen.add(value);
|
|
2028
|
+
try {
|
|
2029
|
+
if (Array.isArray(value)) {
|
|
2030
|
+
return `[${value.map(item => safeCanonicalizeForHash(item, seen)).join(',')}]`;
|
|
2031
|
+
}
|
|
2032
|
+
const keys = Object.keys(value).sort(codePointCompare);
|
|
2033
|
+
const entries = [];
|
|
2034
|
+
for (const k of keys) {
|
|
2035
|
+
let propVal;
|
|
2036
|
+
try {
|
|
2037
|
+
propVal = value[k];
|
|
2038
|
+
} catch {
|
|
2039
|
+
entries.push(`${JSON.stringify(k)}:"[unreadable_property]"`);
|
|
2040
|
+
continue;
|
|
2041
|
+
}
|
|
2042
|
+
if (propVal === undefined) continue;
|
|
2043
|
+
entries.push(`${JSON.stringify(k)}:${safeCanonicalizeForHash(propVal, seen)}`);
|
|
2044
|
+
}
|
|
2045
|
+
return `{${entries.join(',')}}`;
|
|
2046
|
+
} finally {
|
|
2047
|
+
seen.delete(value);
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
return '"[unsupported]"';
|
|
2051
|
+
};
|
|
2052
|
+
const unidentifiedCounts = new Map();
|
|
2053
|
+
const makeUnidentifiedBlockedKey = raw => {
|
|
2054
|
+
let serialized;
|
|
2055
|
+
try {
|
|
2056
|
+
serialized = canonicalizeJson(raw);
|
|
2057
|
+
} catch {
|
|
2058
|
+
serialized = safeCanonicalizeForHash(raw);
|
|
2059
|
+
}
|
|
2060
|
+
const baseKey = `unidentified_${crypto.createHash('sha256').update(serialized).digest('hex').slice(0, 12)}`;
|
|
2061
|
+
const count = (unidentifiedCounts.get(baseKey) || 0) + 1;
|
|
2062
|
+
unidentifiedCounts.set(baseKey, count);
|
|
2063
|
+
return count === 1 ? baseKey : `${baseKey}_${count}`;
|
|
2064
|
+
};
|
|
2065
|
+
|
|
2066
|
+
// 1. Applications (strictly submitted-only + fail-closed CV attribution + 2-layer privacy)
|
|
2067
|
+
for (const raw of applications) {
|
|
2068
|
+
const elig = checkApplicationSyncEligibility(raw, { allCvRegistry });
|
|
2069
|
+
if (!elig.eligible) {
|
|
2070
|
+
if (elig.block_code === 'third_party_subject') {
|
|
2071
|
+
const blockedKey = isObj(raw) && isUsableJobId(raw.job_id)
|
|
2072
|
+
? computeApplicationId(raw.job_id)
|
|
2073
|
+
: makeUnidentifiedBlockedKey(raw);
|
|
2074
|
+
blockedItems.push({
|
|
2075
|
+
database: 'applications',
|
|
2076
|
+
canonical_key: blockedKey,
|
|
2077
|
+
state: 'blocked_privacy',
|
|
2078
|
+
violations: elig.violations,
|
|
2079
|
+
});
|
|
2080
|
+
} else {
|
|
2081
|
+
skippedIneligible.push({
|
|
2082
|
+
canonical_key: elig.canonical_key || 'unknown',
|
|
2083
|
+
status: typeof raw?.status === 'string' ? raw.status : 'unknown',
|
|
2084
|
+
reason: elig.reason || 'ineligible',
|
|
2085
|
+
});
|
|
2086
|
+
}
|
|
2087
|
+
continue;
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
const payload = projectApplicationForNotion(raw, { allCvRegistry });
|
|
2091
|
+
const scan = scanNotionPayloadPrivacy('applications', raw, payload, { allCvRegistry });
|
|
2092
|
+
if (!scan.safe) {
|
|
2093
|
+
blockedItems.push({
|
|
2094
|
+
database: 'applications',
|
|
2095
|
+
canonical_key: elig.canonical_key,
|
|
2096
|
+
state: 'blocked_privacy',
|
|
2097
|
+
violations: scan.violations,
|
|
2098
|
+
});
|
|
2099
|
+
continue;
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
resolveDiffAction({
|
|
2103
|
+
database: 'applications',
|
|
2104
|
+
canonicalKey: elig.canonical_key,
|
|
2105
|
+
applicationStatus: elig.canonical_status,
|
|
2106
|
+
payload,
|
|
2107
|
+
});
|
|
2108
|
+
}
|
|
2109
|
+
|
|
2110
|
+
// 2. Daily Runs (terminal completed/aborted runs only)
|
|
2111
|
+
for (const runDoc of dailyRuns) {
|
|
2112
|
+
const keyRes = resolveCanonicalSyncKey('daily_runs', runDoc);
|
|
2113
|
+
const check = validateDailyRun(runDoc);
|
|
2114
|
+
if (!keyRes.valid || !check.valid) {
|
|
2115
|
+
skippedIneligible.push({
|
|
2116
|
+
canonical_key: keyRes.valid ? keyRes.canonical_key : 'unknown_daily_run',
|
|
2117
|
+
status: typeof runDoc?.status === 'string' ? runDoc.status : 'invalid',
|
|
2118
|
+
reason: !keyRes.valid ? keyRes.reason : 'invalid_daily_run',
|
|
2119
|
+
});
|
|
2120
|
+
continue;
|
|
2121
|
+
}
|
|
2122
|
+
if (runDoc.status !== 'completed' && runDoc.status !== 'aborted') {
|
|
2123
|
+
skippedIneligible.push({
|
|
2124
|
+
canonical_key: keyRes.canonical_key,
|
|
2125
|
+
status: runDoc.status,
|
|
2126
|
+
reason: 'run_not_terminal',
|
|
2127
|
+
});
|
|
2128
|
+
continue;
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
const payload = projectDailyRunForNotion(runDoc);
|
|
2132
|
+
const scan = scanNotionPayloadPrivacy('daily_runs', runDoc, payload);
|
|
2133
|
+
if (!scan.safe) {
|
|
2134
|
+
blockedItems.push({
|
|
2135
|
+
database: 'daily_runs',
|
|
2136
|
+
canonical_key: keyRes.canonical_key,
|
|
2137
|
+
state: 'blocked_privacy',
|
|
2138
|
+
violations: scan.violations,
|
|
2139
|
+
});
|
|
2140
|
+
continue;
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
resolveDiffAction({
|
|
2144
|
+
database: 'daily_runs',
|
|
2145
|
+
canonicalKey: keyRes.canonical_key,
|
|
2146
|
+
payload,
|
|
2147
|
+
});
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
// 3. Weekly & Monthly Insights
|
|
2151
|
+
for (const insightDoc of insights) {
|
|
2152
|
+
const keyRes = resolveCanonicalSyncKey('insights', insightDoc);
|
|
2153
|
+
const check = validateCareerInsights(insightDoc);
|
|
2154
|
+
if (!keyRes.valid || !check.valid) {
|
|
2155
|
+
skippedIneligible.push({
|
|
2156
|
+
canonical_key: keyRes.valid ? keyRes.canonical_key : 'unknown_insight',
|
|
2157
|
+
status: typeof insightDoc?.type === 'string' ? insightDoc.type : 'invalid',
|
|
2158
|
+
reason: !keyRes.valid ? keyRes.reason : 'invalid_career_insight',
|
|
2159
|
+
});
|
|
2160
|
+
continue;
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
const payload = projectInsightForNotion(insightDoc);
|
|
2164
|
+
const scan = scanNotionPayloadPrivacy('insights', insightDoc, payload);
|
|
2165
|
+
if (!scan.safe) {
|
|
2166
|
+
blockedItems.push({
|
|
2167
|
+
database: 'insights',
|
|
2168
|
+
canonical_key: keyRes.canonical_key,
|
|
2169
|
+
state: 'blocked_privacy',
|
|
2170
|
+
violations: scan.violations,
|
|
2171
|
+
});
|
|
2172
|
+
continue;
|
|
2173
|
+
}
|
|
2174
|
+
|
|
2175
|
+
resolveDiffAction({
|
|
2176
|
+
database: 'insights',
|
|
2177
|
+
canonicalKey: keyRes.canonical_key,
|
|
2178
|
+
payload,
|
|
2179
|
+
});
|
|
2180
|
+
}
|
|
2181
|
+
|
|
2182
|
+
// Deterministic canonical sorting on all output arrays
|
|
2183
|
+
operations.sort((a, b) =>
|
|
2184
|
+
codePointCompare(a.database, b.database) ||
|
|
2185
|
+
codePointCompare(a.canonical_key, b.canonical_key) ||
|
|
2186
|
+
codePointCompare(a.operation_id, b.operation_id),
|
|
2187
|
+
);
|
|
2188
|
+
blockedItems.sort((a, b) =>
|
|
2189
|
+
codePointCompare(a.database, b.database) ||
|
|
2190
|
+
codePointCompare(a.canonical_key, b.canonical_key),
|
|
2191
|
+
);
|
|
2192
|
+
skippedIneligible.sort((a, b) =>
|
|
2193
|
+
codePointCompare(a.canonical_key, b.canonical_key) ||
|
|
2194
|
+
codePointCompare(a.status, b.status) ||
|
|
2195
|
+
codePointCompare(a.reason, b.reason),
|
|
2196
|
+
);
|
|
2197
|
+
heldItems.sort((a, b) =>
|
|
2198
|
+
codePointCompare(a.database, b.database) ||
|
|
2199
|
+
codePointCompare(a.canonical_key, b.canonical_key),
|
|
2200
|
+
);
|
|
2201
|
+
|
|
2202
|
+
const effectivePlanId = isNonEmptyString(planId)
|
|
2203
|
+
? planId.trim()
|
|
2204
|
+
: `plan-${createdAt.slice(0, 10)}`;
|
|
2205
|
+
|
|
2206
|
+
const plan = {
|
|
2207
|
+
schema_version: '1.0',
|
|
2208
|
+
plan_id: effectivePlanId,
|
|
2209
|
+
created_at: createdAt,
|
|
2210
|
+
mode: 'preview',
|
|
2211
|
+
eligibility_policy: 'submitted_only',
|
|
2212
|
+
transport_enabled: Boolean(transportEnabled),
|
|
2213
|
+
dry_run: Boolean(dryRun),
|
|
2214
|
+
approval: null,
|
|
2215
|
+
operations,
|
|
2216
|
+
blocked_items: blockedItems,
|
|
2217
|
+
skipped_ineligible: skippedIneligible,
|
|
2218
|
+
};
|
|
2219
|
+
plan.plan_hash = computePlanHash(plan);
|
|
2220
|
+
|
|
2221
|
+
const planCheck = validateNotionSyncPlan(plan);
|
|
2222
|
+
if (!planCheck.valid) {
|
|
2223
|
+
throw new Error(`Generated sync plan failed self-validation: ${planCheck.errors.join('; ')}`);
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
const summary = {
|
|
2227
|
+
create: operations.filter(o => o.action === 'create').length,
|
|
2228
|
+
update: operations.filter(o => o.action === 'update').length,
|
|
2229
|
+
skip_unchanged: operations.filter(o => o.action === 'skip_unchanged').length,
|
|
2230
|
+
blocked_privacy: blockedItems.length,
|
|
2231
|
+
skipped_ineligible: skippedIneligible.length,
|
|
2232
|
+
held: heldItems.length,
|
|
2233
|
+
};
|
|
2234
|
+
|
|
2235
|
+
return {
|
|
2236
|
+
plan,
|
|
2237
|
+
held_items: heldItems,
|
|
2238
|
+
summary,
|
|
2239
|
+
};
|
|
2240
|
+
}
|
|
2241
|
+
|
|
2242
|
+
// ---------------- Stage 3 (T8-B): Approval Binding, Integrity, Locking, Reservation & Recovery ----------------
|
|
2243
|
+
|
|
2244
|
+
export const DEFAULT_MAX_APPROVAL_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours (D1)
|
|
2245
|
+
export const DEFAULT_STALE_IN_FLIGHT_TIMEOUT_MS = 15 * 60 * 1000; // 15 minutes (D5)
|
|
2246
|
+
export const DEFAULT_STALE_LOCK_AGE_MS = 15 * 60 * 1000; // 15 minutes (D2)
|
|
2247
|
+
export const DEFAULT_MAX_RETRIES = 3; // (D4)
|
|
2248
|
+
export const DEFAULT_MAX_FUTURE_SKEW_MS = 5 * 60 * 1000; // 5 minutes
|
|
2249
|
+
|
|
2250
|
+
const SYNC_STATE_LOCK_FILENAME = '.sync-state.lock';
|
|
2251
|
+
|
|
2252
|
+
// Canonical sync-state transition contract (D3, D4, D5):
|
|
2253
|
+
// - t8b_allowed: edges executable in T8-B (reservation & stale in_flight -> receipt_uncertain)
|
|
2254
|
+
// - t8c_gated: edges reserved for T8-C receipt verification, reconciliation, or failure writers (rejected in T8-B)
|
|
2255
|
+
export const SYNC_STATE_TRANSITIONS = Object.freeze({
|
|
2256
|
+
none: Object.freeze({
|
|
2257
|
+
t8b_allowed: Object.freeze(['in_flight']),
|
|
2258
|
+
t8c_gated: Object.freeze([]),
|
|
2259
|
+
}),
|
|
2260
|
+
pending_sync: Object.freeze({
|
|
2261
|
+
t8b_allowed: Object.freeze(['in_flight']),
|
|
2262
|
+
t8c_gated: Object.freeze([]),
|
|
2263
|
+
}),
|
|
2264
|
+
previewed: Object.freeze({
|
|
2265
|
+
t8b_allowed: Object.freeze(['in_flight']),
|
|
2266
|
+
t8c_gated: Object.freeze([]),
|
|
2267
|
+
}),
|
|
2268
|
+
synced: Object.freeze({
|
|
2269
|
+
t8b_allowed: Object.freeze(['in_flight']),
|
|
2270
|
+
t8c_gated: Object.freeze([]),
|
|
2271
|
+
}),
|
|
2272
|
+
failed_retryable: Object.freeze({
|
|
2273
|
+
t8b_allowed: Object.freeze(['in_flight']),
|
|
2274
|
+
t8c_gated: Object.freeze(['failed_permanent']),
|
|
2275
|
+
}),
|
|
2276
|
+
in_flight: Object.freeze({
|
|
2277
|
+
t8b_allowed: Object.freeze(['receipt_uncertain']),
|
|
2278
|
+
t8c_gated: Object.freeze(['synced', 'failed_retryable', 'failed_permanent', 'conflict_duplicate_remote']),
|
|
2279
|
+
}),
|
|
2280
|
+
receipt_uncertain: Object.freeze({
|
|
2281
|
+
t8b_allowed: Object.freeze([]),
|
|
2282
|
+
t8c_gated: Object.freeze(['synced', 'pending_sync', 'conflict_duplicate_remote']),
|
|
2283
|
+
}),
|
|
2284
|
+
conflict_duplicate_remote: Object.freeze({
|
|
2285
|
+
t8b_allowed: Object.freeze([]),
|
|
2286
|
+
t8c_gated: Object.freeze(['synced', 'pending_sync']),
|
|
2287
|
+
}),
|
|
2288
|
+
failed_permanent: Object.freeze({
|
|
2289
|
+
t8b_allowed: Object.freeze([]),
|
|
2290
|
+
t8c_gated: Object.freeze([]),
|
|
2291
|
+
}),
|
|
2292
|
+
blocked_privacy: Object.freeze({
|
|
2293
|
+
t8b_allowed: Object.freeze([]),
|
|
2294
|
+
t8c_gated: Object.freeze([]),
|
|
2295
|
+
}),
|
|
2296
|
+
ineligible_not_submitted: Object.freeze({
|
|
2297
|
+
t8b_allowed: Object.freeze([]),
|
|
2298
|
+
t8c_gated: Object.freeze([]),
|
|
2299
|
+
}),
|
|
2300
|
+
});
|
|
2301
|
+
|
|
2302
|
+
function hasDisallowedLastErrorContent(str) {
|
|
2303
|
+
if (typeof str !== 'string' || !str.length) return false;
|
|
2304
|
+
if (SECRET_TOKEN_PATTERNS.some(re => re.test(str))) return true;
|
|
2305
|
+
if (EMAIL_RE.test(str)) return true;
|
|
2306
|
+
if (LOCAL_PATH_PATTERNS.some(re => re.test(str))) return true;
|
|
2307
|
+
return false;
|
|
2308
|
+
}
|
|
2309
|
+
|
|
2310
|
+
// D6: Structural & semantic sync-state integrity validation (cross-key page_id uniqueness,
|
|
2311
|
+
// cross-key active in_flight operation_id uniqueness, temporal skew check, last_error privacy).
|
|
2312
|
+
export function verifySyncStateIntegrity(stateDoc, { nowIso = null, maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS } = {}) {
|
|
2313
|
+
const base = validateNotionSyncState(stateDoc);
|
|
2314
|
+
const errors = [...base.errors];
|
|
2315
|
+
const warnings = [...base.warnings];
|
|
2316
|
+
|
|
2317
|
+
if (nowIso !== null && !isValidIsoDateTime(nowIso)) {
|
|
2318
|
+
errors.push(`verifySyncStateIntegrity: invalid nowIso timestamp "${nowIso}".`);
|
|
2319
|
+
}
|
|
2320
|
+
if (!Number.isSafeInteger(maxFutureSkewMs) || maxFutureSkewMs < 0) {
|
|
2321
|
+
errors.push('verifySyncStateIntegrity: maxFutureSkewMs must be a non-negative safe integer.');
|
|
2322
|
+
}
|
|
2323
|
+
if (!base.valid || errors.length > 0) {
|
|
2324
|
+
return { valid: false, errors, warnings };
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
const nowMs = nowIso !== null ? Date.parse(nowIso) : null;
|
|
2328
|
+
const pageOwners = new Map(); // normalized_uuid -> recKey
|
|
2329
|
+
const activeOpOwners = new Map(); // operation_id -> recKey
|
|
2330
|
+
const sortedKeys = Object.keys(stateDoc.records).sort(codePointCompare);
|
|
2331
|
+
|
|
2332
|
+
for (const recKey of sortedKeys) {
|
|
2333
|
+
const entry = stateDoc.records[recKey];
|
|
2334
|
+
const label = `sync_state.records["${recKey}"]`;
|
|
2335
|
+
|
|
2336
|
+
if (entry.page_id !== undefined && entry.page_id !== null) {
|
|
2337
|
+
const normPageId = normalizeNotionUuid(entry.page_id);
|
|
2338
|
+
if (normPageId) {
|
|
2339
|
+
const prevOwner = pageOwners.get(normPageId);
|
|
2340
|
+
if (prevOwner !== undefined && prevOwner !== recKey) {
|
|
2341
|
+
errors.push(`sync_state: duplicate page_id "${normPageId}" owned by both "${prevOwner}" and "${recKey}".`);
|
|
2342
|
+
} else {
|
|
2343
|
+
pageOwners.set(normPageId, recKey);
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
|
|
2348
|
+
if (entry.state === 'in_flight') {
|
|
2349
|
+
const prevOpOwner = activeOpOwners.get(entry.operation_id);
|
|
2350
|
+
if (prevOpOwner !== undefined && prevOpOwner !== recKey) {
|
|
2351
|
+
errors.push(`sync_state: duplicate active in_flight operation_id "${entry.operation_id}" across "${prevOpOwner}" and "${recKey}".`);
|
|
2352
|
+
} else {
|
|
2353
|
+
activeOpOwners.set(entry.operation_id, recKey);
|
|
2354
|
+
}
|
|
2355
|
+
if (nowMs !== null) {
|
|
2356
|
+
const attemptedMs = Date.parse(entry.attempted_at);
|
|
2357
|
+
if (attemptedMs - nowMs > maxFutureSkewMs) {
|
|
2358
|
+
errors.push(`${label}.attempted_at "${entry.attempted_at}" is in the future beyond allowed skew (${maxFutureSkewMs}ms).`);
|
|
2359
|
+
}
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
|
|
2363
|
+
if (typeof entry.last_error === 'string' && hasDisallowedLastErrorContent(entry.last_error)) {
|
|
2364
|
+
errors.push(`${label}.last_error contains disallowed secret, email, or local file path.`);
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
|
|
2368
|
+
// Verify conflicting_page_ids do not collide with another canonical key's owned page_id
|
|
2369
|
+
for (const recKey of sortedKeys) {
|
|
2370
|
+
const entry = stateDoc.records[recKey];
|
|
2371
|
+
if (!Array.isArray(entry.conflicting_page_ids)) continue;
|
|
2372
|
+
for (const cid of entry.conflicting_page_ids) {
|
|
2373
|
+
const normCid = normalizeNotionUuid(cid);
|
|
2374
|
+
if (!normCid) continue;
|
|
2375
|
+
const owner = pageOwners.get(normCid);
|
|
2376
|
+
if (owner !== undefined && owner !== recKey) {
|
|
2377
|
+
errors.push(`sync_state.records["${recKey}"].conflicting_page_ids references page_id "${normCid}" already owned by "${owner}".`);
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
}
|
|
2381
|
+
|
|
2382
|
+
return { valid: errors.length === 0, errors, warnings };
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
// Explicit fail-closed state-transition validator (D3, D4, D5).
|
|
2386
|
+
export function validateSyncStateTransition(currentEntry, targetState, {
|
|
2387
|
+
op = null,
|
|
2388
|
+
nowIso = null,
|
|
2389
|
+
force = false,
|
|
2390
|
+
maxRetries = DEFAULT_MAX_RETRIES,
|
|
2391
|
+
staleTimeoutMs = DEFAULT_STALE_IN_FLIGHT_TIMEOUT_MS,
|
|
2392
|
+
} = {}) {
|
|
2393
|
+
const fail = (code, reason) => ({
|
|
2394
|
+
valid: false,
|
|
2395
|
+
from_state: currentEntry === null || currentEntry === undefined ? 'none' : (currentEntry?.state ?? 'invalid'),
|
|
2396
|
+
to_state: targetState,
|
|
2397
|
+
code,
|
|
2398
|
+
reason,
|
|
2399
|
+
});
|
|
2400
|
+
|
|
2401
|
+
if (typeof force !== 'boolean') {
|
|
2402
|
+
return fail('invalid_force_flag', 'force option must be an explicit boolean.');
|
|
2403
|
+
}
|
|
2404
|
+
if (!SYNC_ITEM_STATES.has(targetState)) {
|
|
2405
|
+
return fail('invalid_target_state', `Target state "${targetState}" is not a valid sync item state.`);
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
let fromState = 'none';
|
|
2409
|
+
if (currentEntry !== null && currentEntry !== undefined) {
|
|
2410
|
+
if (!isObj(currentEntry) || !SYNC_ITEM_STATES.has(currentEntry.state)) {
|
|
2411
|
+
return fail('invalid_current_entry', 'Current sync-state entry is malformed or has an invalid state.');
|
|
2412
|
+
}
|
|
2413
|
+
fromState = currentEntry.state;
|
|
2414
|
+
}
|
|
2415
|
+
|
|
2416
|
+
const rule = SYNC_STATE_TRANSITIONS[fromState];
|
|
2417
|
+
if (!rule) {
|
|
2418
|
+
return fail('unknown_from_state', `No transition rule defined for state "${fromState}".`);
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
if (rule.t8c_gated.includes(targetState)) {
|
|
2422
|
+
return fail(
|
|
2423
|
+
'requires_t8c_receipt_or_reconciliation',
|
|
2424
|
+
`Transition "${fromState}" -> "${targetState}" requires T8-C receipt verification, reconciliation, or failure handling and is blocked in T8-B.`,
|
|
2425
|
+
);
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
if (!rule.t8b_allowed.includes(targetState)) {
|
|
2429
|
+
if (fromState === 'in_flight' && targetState === 'in_flight') {
|
|
2430
|
+
return fail('already_in_flight', 'Record is already in_flight; duplicate reservation is forbidden.');
|
|
2431
|
+
}
|
|
2432
|
+
if (fromState === 'failed_permanent') {
|
|
2433
|
+
return fail('failed_permanent_held', 'Record is in failed_permanent and remains manually held; neither force nor payload changes reset it.');
|
|
2434
|
+
}
|
|
2435
|
+
if (fromState === 'receipt_uncertain' || fromState === 'conflict_duplicate_remote') {
|
|
2436
|
+
return fail('requires_reconciliation', `Record is in "${fromState}" and requires remote reconciliation; force cannot bypass it.`);
|
|
2437
|
+
}
|
|
2438
|
+
if (fromState === 'blocked_privacy' || fromState === 'ineligible_not_submitted') {
|
|
2439
|
+
return fail('blocked_or_ineligible', `Record is in "${fromState}" and cannot enter execution.`);
|
|
2440
|
+
}
|
|
2441
|
+
return fail('transition_not_allowed', `Transition "${fromState}" -> "${targetState}" is not allowed.`);
|
|
2442
|
+
}
|
|
2443
|
+
|
|
2444
|
+
if (targetState === 'in_flight') {
|
|
2445
|
+
if (!isObj(op) || (op.action !== 'create' && op.action !== 'update')) {
|
|
2446
|
+
return fail('non_mutating_or_missing_operation', 'Reserving in_flight requires a valid "create" or "update" operation (skip_unchanged cannot reserve).');
|
|
2447
|
+
}
|
|
2448
|
+
if (typeof op.sync_hash !== 'string' || !HEX16_RE.test(op.sync_hash)) {
|
|
2449
|
+
return fail('invalid_operation_hash', 'Operation sync_hash must be a 16-char lowercase hex string.');
|
|
2450
|
+
}
|
|
2451
|
+
|
|
2452
|
+
const existingPageId = currentEntry?.page_id !== undefined && currentEntry?.page_id !== null
|
|
2453
|
+
? normalizeNotionUuid(currentEntry.page_id)
|
|
2454
|
+
: null;
|
|
2455
|
+
|
|
2456
|
+
if (op.action === 'create') {
|
|
2457
|
+
if (op.existing_page_id !== null && op.existing_page_id !== undefined) {
|
|
2458
|
+
return fail('create_with_existing_page_id', 'Create operation cannot specify a non-null existing_page_id.');
|
|
2459
|
+
}
|
|
2460
|
+
if (fromState === 'synced') {
|
|
2461
|
+
return fail('create_target_already_synced', 'Cannot reserve create for a canonical key already in synced state.');
|
|
2462
|
+
}
|
|
2463
|
+
if (existingPageId !== null) {
|
|
2464
|
+
return fail('create_target_already_has_page_id', `Cannot reserve create when sync state already holds page_id "${existingPageId}".`);
|
|
2465
|
+
}
|
|
2466
|
+
} else if (op.action === 'update') {
|
|
2467
|
+
const targetPageId = normalizeNotionUuid(op.existing_page_id);
|
|
2468
|
+
if (!targetPageId) {
|
|
2469
|
+
return fail('update_missing_page_id', 'Update operation requires a valid Notion UUID existing_page_id.');
|
|
2470
|
+
}
|
|
2471
|
+
if (existingPageId !== null && existingPageId !== targetPageId) {
|
|
2472
|
+
return fail('update_page_id_mismatch', `Plan update existing_page_id "${targetPageId}" contradicts sync-state page_id "${existingPageId}".`);
|
|
2473
|
+
}
|
|
2474
|
+
if (fromState === 'synced' && currentEntry.last_synced_hash === op.sync_hash) {
|
|
2475
|
+
return fail('already_synced_unchanged', 'Record is already synced with the exact same sync_hash; redundant update refused.');
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
|
|
2479
|
+
// D4: failed_retryable cooldown & retry cap (ONLY state where explicit force may bypass cooldown/cap)
|
|
2480
|
+
if (fromState === 'failed_retryable') {
|
|
2481
|
+
if (!Number.isSafeInteger(maxRetries) || maxRetries < 1) {
|
|
2482
|
+
return fail('invalid_max_retries', 'maxRetries must be a positive safe integer.');
|
|
2483
|
+
}
|
|
2484
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
2485
|
+
return fail('invalid_now_iso', 'Valid ISO-8601 nowIso is required to evaluate failed_retryable cooldown.');
|
|
2486
|
+
}
|
|
2487
|
+
const retryCount = Number.isInteger(currentEntry.retry_count) ? currentEntry.retry_count : 0;
|
|
2488
|
+
if (!force) {
|
|
2489
|
+
if (retryCount >= maxRetries) {
|
|
2490
|
+
return fail('retry_cap_reached', `failed_retryable retry_count (${retryCount}) reached maxRetries (${maxRetries}); explicit force required to retry.`);
|
|
2491
|
+
}
|
|
2492
|
+
if (currentEntry.next_retry_after !== undefined && currentEntry.next_retry_after !== null) {
|
|
2493
|
+
if (!isValidIsoDateTime(currentEntry.next_retry_after)) {
|
|
2494
|
+
return fail('invalid_next_retry_after', 'failed_retryable entry has invalid next_retry_after timestamp.');
|
|
2495
|
+
}
|
|
2496
|
+
if (Date.parse(nowIso) < Date.parse(currentEntry.next_retry_after)) {
|
|
2497
|
+
return fail('retry_cooldown_active', `failed_retryable cooldown active until "${currentEntry.next_retry_after}".`);
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
}
|
|
2502
|
+
}
|
|
2503
|
+
|
|
2504
|
+
if (fromState === 'in_flight' && targetState === 'receipt_uncertain') {
|
|
2505
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
2506
|
+
return fail('invalid_now_iso', 'Valid ISO-8601 nowIso is required to evaluate in_flight staleness.');
|
|
2507
|
+
}
|
|
2508
|
+
if (!Number.isSafeInteger(staleTimeoutMs) || staleTimeoutMs <= 0) {
|
|
2509
|
+
return fail('invalid_stale_timeout', 'staleTimeoutMs must be a positive safe integer.');
|
|
2510
|
+
}
|
|
2511
|
+
if (!isValidIsoDateTime(currentEntry.attempted_at)) {
|
|
2512
|
+
return fail('invalid_attempted_at', 'in_flight entry is missing a valid ISO-8601 attempted_at timestamp.');
|
|
2513
|
+
}
|
|
2514
|
+
const ageMs = Date.parse(nowIso) - Date.parse(currentEntry.attempted_at);
|
|
2515
|
+
if (ageMs < staleTimeoutMs) {
|
|
2516
|
+
return fail('in_flight_not_stale', `in_flight entry age (${ageMs}ms) has not reached staleTimeoutMs (${staleTimeoutMs}ms).`);
|
|
2517
|
+
}
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2520
|
+
return {
|
|
2521
|
+
valid: true,
|
|
2522
|
+
from_state: fromState,
|
|
2523
|
+
to_state: targetState,
|
|
2524
|
+
code: null,
|
|
2525
|
+
reason: null,
|
|
2526
|
+
};
|
|
2527
|
+
}
|
|
2528
|
+
|
|
2529
|
+
// D1: Plan-bound approval tied strictly to immutable plan_hash.
|
|
2530
|
+
export function approveNotionSyncPlan(previewPlan, {
|
|
2531
|
+
expectedPlanHash,
|
|
2532
|
+
confirmedByOwner = false,
|
|
2533
|
+
approvedAt = new Date().toISOString(),
|
|
2534
|
+
} = {}) {
|
|
2535
|
+
if (confirmedByOwner !== true) {
|
|
2536
|
+
throw new Error('approveNotionSyncPlan requires explicit confirmedByOwner === true.');
|
|
2537
|
+
}
|
|
2538
|
+
if (typeof expectedPlanHash !== 'string' || !HEX64_RE.test(expectedPlanHash)) {
|
|
2539
|
+
throw new Error('approveNotionSyncPlan requires a valid 64-char lowercase hex expectedPlanHash.');
|
|
2540
|
+
}
|
|
2541
|
+
if (!isValidIsoDateTime(approvedAt)) {
|
|
2542
|
+
throw new Error(`approveNotionSyncPlan: invalid approvedAt timestamp "${approvedAt}".`);
|
|
2543
|
+
}
|
|
2544
|
+
|
|
2545
|
+
const check = validateNotionSyncPlan(previewPlan);
|
|
2546
|
+
if (!check.valid) {
|
|
2547
|
+
throw new Error(`Cannot approve invalid sync plan: ${check.errors.join('; ')}`);
|
|
2548
|
+
}
|
|
2549
|
+
if (previewPlan.mode !== 'preview') {
|
|
2550
|
+
throw new Error(`Cannot approve plan in mode "${previewPlan.mode}"; only "preview" plans can be approved.`);
|
|
2551
|
+
}
|
|
2552
|
+
if (previewPlan.approval !== null && previewPlan.approval !== undefined) {
|
|
2553
|
+
throw new Error('Cannot approve plan that already carries approval metadata.');
|
|
2554
|
+
}
|
|
2555
|
+
if (previewPlan.dry_run !== false) {
|
|
2556
|
+
throw new Error('Cannot approve a dry_run=true plan for execution; generate a live-eligible preview first.');
|
|
2557
|
+
}
|
|
2558
|
+
if (previewPlan.transport_enabled !== true) {
|
|
2559
|
+
throw new Error('Cannot approve a transport_enabled=false plan for execution.');
|
|
2560
|
+
}
|
|
2561
|
+
if (previewPlan.plan_hash !== expectedPlanHash) {
|
|
2562
|
+
throw new Error(`Approval hash mismatch: expected "${expectedPlanHash}", got "${previewPlan.plan_hash}".`);
|
|
2563
|
+
}
|
|
2564
|
+
const recomputed = computePlanHash(previewPlan);
|
|
2565
|
+
if (recomputed !== expectedPlanHash) {
|
|
2566
|
+
throw new Error(`Recomputed plan_hash "${recomputed}" does not match expectedPlanHash "${expectedPlanHash}".`);
|
|
2567
|
+
}
|
|
2568
|
+
if (Date.parse(approvedAt) < Date.parse(previewPlan.created_at)) {
|
|
2569
|
+
throw new Error(`approvedAt "${approvedAt}" cannot predate plan created_at "${previewPlan.created_at}".`);
|
|
2570
|
+
}
|
|
2571
|
+
|
|
2572
|
+
// Deep-clone so post-approval mutations to previewPlan cannot tamper with the approved artifact
|
|
2573
|
+
const approvedPlan = JSON.parse(JSON.stringify(previewPlan));
|
|
2574
|
+
approvedPlan.mode = 'approved_execute';
|
|
2575
|
+
approvedPlan.approval = {
|
|
2576
|
+
approved_plan_hash: recomputed,
|
|
2577
|
+
approved_plan_id: approvedPlan.plan_id,
|
|
2578
|
+
approved_at: approvedAt,
|
|
2579
|
+
approved_by: 'owner',
|
|
2580
|
+
operation_count: approvedPlan.operations.length,
|
|
2581
|
+
};
|
|
2582
|
+
|
|
2583
|
+
const postCheck = validateNotionSyncPlan(approvedPlan);
|
|
2584
|
+
if (!postCheck.valid) {
|
|
2585
|
+
throw new Error(`Approved sync plan failed self-validation: ${postCheck.errors.join('; ')}`);
|
|
2586
|
+
}
|
|
2587
|
+
return approvedPlan;
|
|
2588
|
+
}
|
|
2589
|
+
|
|
2590
|
+
// D1: Verify approved plan integrity, live flags, causality & TTL expiration.
|
|
2591
|
+
export function verifyPlanApproval(plan, {
|
|
2592
|
+
nowIso = new Date().toISOString(),
|
|
2593
|
+
maxApprovalAgeMs = DEFAULT_MAX_APPROVAL_AGE_MS,
|
|
2594
|
+
} = {}) {
|
|
2595
|
+
const errors = [];
|
|
2596
|
+
let code = null;
|
|
2597
|
+
const setErr = (errCode, msg) => {
|
|
2598
|
+
if (code === null) code = errCode;
|
|
2599
|
+
errors.push(msg);
|
|
2600
|
+
};
|
|
2601
|
+
|
|
2602
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
2603
|
+
setErr('invalid_now_iso', `verifyPlanApproval: invalid nowIso timestamp "${nowIso}".`);
|
|
2604
|
+
}
|
|
2605
|
+
if (!Number.isSafeInteger(maxApprovalAgeMs) || maxApprovalAgeMs <= 0) {
|
|
2606
|
+
setErr('invalid_max_approval_age_ms', 'verifyPlanApproval: maxApprovalAgeMs must be a positive safe integer.');
|
|
2607
|
+
}
|
|
2608
|
+
|
|
2609
|
+
const planCheck = validateNotionSyncPlan(plan);
|
|
2610
|
+
if (!planCheck.valid) {
|
|
2611
|
+
setErr('invalid_or_tampered_plan', `Plan validation failed: ${planCheck.errors.join('; ')}`);
|
|
2612
|
+
return { valid: false, code, errors, age_ms: null, expires_at: null };
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2615
|
+
if (plan.mode !== 'approved_execute') {
|
|
2616
|
+
setErr('plan_not_approved_execute', `Plan mode must be "approved_execute" (got "${plan.mode}").`);
|
|
2617
|
+
}
|
|
2618
|
+
if (plan.dry_run !== false) {
|
|
2619
|
+
setErr('plan_is_dry_run', 'Approved execution rejected because plan.dry_run is true.');
|
|
2620
|
+
}
|
|
2621
|
+
if (plan.transport_enabled !== true) {
|
|
2622
|
+
setErr('plan_transport_disabled', 'Approved execution rejected because plan.transport_enabled is false.');
|
|
2623
|
+
}
|
|
2624
|
+
if (!isObj(plan.approval)) {
|
|
2625
|
+
setErr('missing_approval', 'Approved plan is missing approval metadata.');
|
|
2626
|
+
return { valid: false, code, errors, age_ms: null, expires_at: null };
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
const recomputed = computePlanHash(plan);
|
|
2630
|
+
if (recomputed !== plan.plan_hash || recomputed !== plan.approval.approved_plan_hash) {
|
|
2631
|
+
setErr('plan_hash_mismatch', 'Plan hash no longer matches approved_plan_hash.');
|
|
2632
|
+
}
|
|
2633
|
+
|
|
2634
|
+
const createdMs = Date.parse(plan.created_at);
|
|
2635
|
+
const approvedMs = Date.parse(plan.approval.approved_at);
|
|
2636
|
+
const nowMs = isValidIsoDateTime(nowIso) ? Date.parse(nowIso) : NaN;
|
|
2637
|
+
const expiresAt = Number.isSafeInteger(maxApprovalAgeMs) && maxApprovalAgeMs > 0
|
|
2638
|
+
? new Date(approvedMs + maxApprovalAgeMs).toISOString()
|
|
2639
|
+
: null;
|
|
2640
|
+
|
|
2641
|
+
if (approvedMs < createdMs) {
|
|
2642
|
+
setErr('approval_predates_plan', `approval.approved_at "${plan.approval.approved_at}" predates plan.created_at "${plan.created_at}".`);
|
|
2643
|
+
}
|
|
2644
|
+
|
|
2645
|
+
let ageMs = null;
|
|
2646
|
+
if (!Number.isNaN(nowMs)) {
|
|
2647
|
+
ageMs = nowMs - approvedMs;
|
|
2648
|
+
if (ageMs < 0) {
|
|
2649
|
+
setErr('approval_timestamp_in_future', `approval.approved_at "${plan.approval.approved_at}" is in the future relative to nowIso "${nowIso}".`);
|
|
2650
|
+
} else if (Number.isSafeInteger(maxApprovalAgeMs) && maxApprovalAgeMs > 0 && ageMs > maxApprovalAgeMs) {
|
|
2651
|
+
setErr('approval_expired', `Approval expired at "${expiresAt}" (age ${ageMs}ms exceeds maxApprovalAgeMs ${maxApprovalAgeMs}ms).`);
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
|
|
2655
|
+
return {
|
|
2656
|
+
valid: errors.length === 0,
|
|
2657
|
+
code,
|
|
2658
|
+
errors,
|
|
2659
|
+
age_ms: ageMs,
|
|
2660
|
+
expires_at: expiresAt,
|
|
2661
|
+
};
|
|
2662
|
+
}
|
|
2663
|
+
|
|
2664
|
+
// D2: Strict exclusive single-writer lockfile (no automatic stale-lock stealing).
|
|
2665
|
+
function isProcessAlive(pid) {
|
|
2666
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return true; // Fail closed: invalid PID cannot be assumed dead
|
|
2667
|
+
try {
|
|
2668
|
+
process.kill(pid, 0);
|
|
2669
|
+
return true;
|
|
2670
|
+
} catch (err) {
|
|
2671
|
+
if (err && err.code === 'ESRCH') return false;
|
|
2672
|
+
return true; // EPERM or unknown error -> assume process exists (fail closed)
|
|
2673
|
+
}
|
|
2674
|
+
}
|
|
2675
|
+
|
|
2676
|
+
function getSyncStateLockPath(root) {
|
|
2677
|
+
if (!isNonEmptyString(root)) {
|
|
2678
|
+
throw new Error('Workspace root path must be a non-empty string.');
|
|
2679
|
+
}
|
|
2680
|
+
return path.join(root, 'logs', SYNC_STATE_LOCK_FILENAME);
|
|
2681
|
+
}
|
|
2682
|
+
|
|
2683
|
+
function acquireSyncStateLock(root, { home = os.homedir(), nowIso } = {}) {
|
|
2684
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
2685
|
+
throw new Error(`acquireSyncStateLock: invalid nowIso timestamp "${nowIso}".`);
|
|
2686
|
+
}
|
|
2687
|
+
const logsDir = path.join(root, 'logs');
|
|
2688
|
+
const lockPath = getSyncStateLockPath(root);
|
|
2689
|
+
refuseSymlink(logsDir, root, home);
|
|
2690
|
+
refuseSymlink(lockPath, root, home);
|
|
2691
|
+
fs.mkdirSync(logsDir, { recursive: true });
|
|
2692
|
+
refuseSymlink(lockPath, root, home);
|
|
2693
|
+
|
|
2694
|
+
const nonce = crypto.randomBytes(16).toString('hex');
|
|
2695
|
+
const payload = JSON.stringify({
|
|
2696
|
+
pid: process.pid,
|
|
2697
|
+
acquired_at: nowIso,
|
|
2698
|
+
nonce,
|
|
2699
|
+
}, null, 2) + '\n';
|
|
2700
|
+
|
|
2701
|
+
let fd;
|
|
2702
|
+
try {
|
|
2703
|
+
fd = fs.openSync(lockPath, 'wx', 0o600);
|
|
2704
|
+
} catch (err) {
|
|
2705
|
+
if (err && err.code === 'EEXIST') {
|
|
2706
|
+
throw new Error(`sync_state_locked: "${lockPath}" is already held; refusing concurrent write without stealing lock.`);
|
|
2707
|
+
}
|
|
2708
|
+
throw err;
|
|
2709
|
+
}
|
|
2710
|
+
|
|
2711
|
+
try {
|
|
2712
|
+
fs.writeFileSync(fd, payload, 'utf8');
|
|
2713
|
+
} catch (err) {
|
|
2714
|
+
try { fs.closeSync(fd); } catch { /* ignore */ }
|
|
2715
|
+
try { fs.unlinkSync(lockPath); } catch { /* ignore */ }
|
|
2716
|
+
throw err;
|
|
2717
|
+
}
|
|
2718
|
+
fs.closeSync(fd);
|
|
2719
|
+
if (process.platform !== 'win32') {
|
|
2720
|
+
try { fs.chmodSync(lockPath, 0o600); } catch { /* ignore */ }
|
|
2721
|
+
}
|
|
2722
|
+
return { lockPath, nonce };
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
function releaseOwnSyncStateLock(lockHandle, { root, home = os.homedir() } = {}) {
|
|
2726
|
+
if (!lockHandle) return;
|
|
2727
|
+
refuseSymlink(lockHandle.lockPath, root, home);
|
|
2728
|
+
if (!fs.existsSync(lockHandle.lockPath)) return;
|
|
2729
|
+
let parsed;
|
|
2730
|
+
try {
|
|
2731
|
+
parsed = JSON.parse(fs.readFileSync(lockHandle.lockPath, 'utf8'));
|
|
2732
|
+
} catch {
|
|
2733
|
+
return; // Never unlink a lock we cannot prove is ours
|
|
2734
|
+
}
|
|
2735
|
+
if (isObj(parsed) && parsed.nonce === lockHandle.nonce) {
|
|
2736
|
+
fs.unlinkSync(lockHandle.lockPath);
|
|
2737
|
+
}
|
|
2738
|
+
}
|
|
2739
|
+
|
|
2740
|
+
function withSyncStateLock(root, { home = os.homedir(), nowIso } = {}, fn) {
|
|
2741
|
+
const handle = acquireSyncStateLock(root, { home, nowIso });
|
|
2742
|
+
try {
|
|
2743
|
+
return fn();
|
|
2744
|
+
} finally {
|
|
2745
|
+
releaseOwnSyncStateLock(handle, { root, home });
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
|
|
2749
|
+
// D2: Read-only lockfile inspection (never modifies or deletes the lock).
|
|
2750
|
+
export function inspectSyncStateLock(root, {
|
|
2751
|
+
home = os.homedir(),
|
|
2752
|
+
nowIso = new Date().toISOString(),
|
|
2753
|
+
staleLockAgeMs = DEFAULT_STALE_LOCK_AGE_MS,
|
|
2754
|
+
} = {}) {
|
|
2755
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
2756
|
+
throw new Error(`inspectSyncStateLock: invalid nowIso timestamp "${nowIso}".`);
|
|
2757
|
+
}
|
|
2758
|
+
if (!Number.isSafeInteger(staleLockAgeMs) || staleLockAgeMs <= 0) {
|
|
2759
|
+
throw new Error('inspectSyncStateLock: staleLockAgeMs must be a positive safe integer.');
|
|
2760
|
+
}
|
|
2761
|
+
const lockPath = getSyncStateLockPath(root);
|
|
2762
|
+
refuseSymlink(lockPath, root, home);
|
|
2763
|
+
if (!fs.existsSync(lockPath)) {
|
|
2764
|
+
return {
|
|
2765
|
+
locked: false,
|
|
2766
|
+
path: lockPath,
|
|
2767
|
+
corrupt: false,
|
|
2768
|
+
stale: false,
|
|
2769
|
+
owner_alive: null,
|
|
2770
|
+
age_ms: null,
|
|
2771
|
+
lock: null,
|
|
2772
|
+
error: null,
|
|
2773
|
+
};
|
|
2774
|
+
}
|
|
2775
|
+
|
|
2776
|
+
let parsed;
|
|
2777
|
+
try {
|
|
2778
|
+
parsed = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
|
|
2779
|
+
} catch (err) {
|
|
2780
|
+
return {
|
|
2781
|
+
locked: true,
|
|
2782
|
+
path: lockPath,
|
|
2783
|
+
corrupt: true,
|
|
2784
|
+
stale: false,
|
|
2785
|
+
owner_alive: null,
|
|
2786
|
+
age_ms: null,
|
|
2787
|
+
lock: null,
|
|
2788
|
+
error: `Corrupt lockfile JSON: ${err.message}`,
|
|
2789
|
+
};
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2792
|
+
const validShape = isObj(parsed) &&
|
|
2793
|
+
Number.isSafeInteger(parsed.pid) && parsed.pid > 0 &&
|
|
2794
|
+
isValidIsoDateTime(parsed.acquired_at) &&
|
|
2795
|
+
isNonEmptyString(parsed.nonce);
|
|
2796
|
+
if (!validShape) {
|
|
2797
|
+
return {
|
|
2798
|
+
locked: true,
|
|
2799
|
+
path: lockPath,
|
|
2800
|
+
corrupt: true,
|
|
2801
|
+
stale: false,
|
|
2802
|
+
owner_alive: null,
|
|
2803
|
+
age_ms: null,
|
|
2804
|
+
lock: null,
|
|
2805
|
+
error: 'Lockfile metadata is malformed (missing valid pid, acquired_at, or nonce).',
|
|
2806
|
+
};
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
const ageMs = Date.parse(nowIso) - Date.parse(parsed.acquired_at);
|
|
2810
|
+
const ownerAlive = isProcessAlive(parsed.pid);
|
|
2811
|
+
return {
|
|
2812
|
+
locked: true,
|
|
2813
|
+
path: lockPath,
|
|
2814
|
+
corrupt: false,
|
|
2815
|
+
stale: ageMs >= staleLockAgeMs,
|
|
2816
|
+
owner_alive: ownerAlive,
|
|
2817
|
+
age_ms: ageMs,
|
|
2818
|
+
lock: {
|
|
2819
|
+
pid: parsed.pid,
|
|
2820
|
+
acquired_at: parsed.acquired_at,
|
|
2821
|
+
nonce: parsed.nonce,
|
|
2822
|
+
},
|
|
2823
|
+
error: null,
|
|
2824
|
+
};
|
|
2825
|
+
}
|
|
2826
|
+
|
|
2827
|
+
// D2: Separate explicit stale-lock recovery action — never called automatically.
|
|
2828
|
+
// Refuses removal unless explicitly confirmed, expectedNonce matches, lock is stale, and owning PID is confirmed dead.
|
|
2829
|
+
export function releaseStaleSyncStateLock(root, {
|
|
2830
|
+
home = os.homedir(),
|
|
2831
|
+
nowIso = new Date().toISOString(),
|
|
2832
|
+
staleLockAgeMs = DEFAULT_STALE_LOCK_AGE_MS,
|
|
2833
|
+
expectedNonce,
|
|
2834
|
+
confirmedExplicitRecovery = false,
|
|
2835
|
+
} = {}) {
|
|
2836
|
+
if (confirmedExplicitRecovery !== true) {
|
|
2837
|
+
throw new Error('releaseStaleSyncStateLock requires explicit confirmedExplicitRecovery === true.');
|
|
2838
|
+
}
|
|
2839
|
+
if (!isNonEmptyString(expectedNonce)) {
|
|
2840
|
+
throw new Error('releaseStaleSyncStateLock requires a non-empty expectedNonce to prevent TOCTOU races.');
|
|
2841
|
+
}
|
|
2842
|
+
const info = inspectSyncStateLock(root, { home, nowIso, staleLockAgeMs });
|
|
2843
|
+
if (!info.locked) {
|
|
2844
|
+
throw new Error('No sync-state lockfile exists to release.');
|
|
2845
|
+
}
|
|
2846
|
+
if (info.corrupt || !info.lock) {
|
|
2847
|
+
throw new Error(`Refusing automatic removal of corrupt lockfile: ${info.error}`);
|
|
2848
|
+
}
|
|
2849
|
+
if (info.lock.nonce !== expectedNonce) {
|
|
2850
|
+
throw new Error('Lockfile nonce mismatch; refusing stale-lock release because lock ownership changed.');
|
|
2851
|
+
}
|
|
2852
|
+
if (!info.stale) {
|
|
2853
|
+
throw new Error(`Refusing stale-lock release: lock age (${info.age_ms}ms) is below staleLockAgeMs (${staleLockAgeMs}ms).`);
|
|
2854
|
+
}
|
|
2855
|
+
if (info.lock.pid === process.pid || info.owner_alive !== false) {
|
|
2856
|
+
throw new Error(`Refusing stale-lock release: owning PID ${info.lock.pid} is still active or cannot be proven dead.`);
|
|
2857
|
+
}
|
|
2858
|
+
|
|
2859
|
+
// Final re-check immediately before unlink to guard against concurrent replacement
|
|
2860
|
+
refuseSymlink(info.path, root, home);
|
|
2861
|
+
const reread = JSON.parse(fs.readFileSync(info.path, 'utf8'));
|
|
2862
|
+
if (!isObj(reread) || reread.nonce !== expectedNonce) {
|
|
2863
|
+
throw new Error('Lockfile changed during stale-lock release; aborting safely.');
|
|
2864
|
+
}
|
|
2865
|
+
fs.unlinkSync(info.path);
|
|
2866
|
+
return {
|
|
2867
|
+
released: true,
|
|
2868
|
+
path: info.path,
|
|
2869
|
+
released_pid: info.lock.pid,
|
|
2870
|
+
released_nonce: info.lock.nonce,
|
|
2871
|
+
age_ms: info.age_ms,
|
|
2872
|
+
};
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
// Atomic, verified pre-write in_flight reservation (D1, D2, D4, D5, D6).
|
|
2876
|
+
export function reserveOperationInFlight(root, {
|
|
2877
|
+
approvedPlan,
|
|
2878
|
+
operationId,
|
|
2879
|
+
nowIso = new Date().toISOString(),
|
|
2880
|
+
force = false,
|
|
2881
|
+
maxRetries = DEFAULT_MAX_RETRIES,
|
|
2882
|
+
maxApprovalAgeMs = DEFAULT_MAX_APPROVAL_AGE_MS,
|
|
2883
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
2884
|
+
home = os.homedir(),
|
|
2885
|
+
} = {}) {
|
|
2886
|
+
if (!isNonEmptyString(root)) {
|
|
2887
|
+
throw new Error('reserveOperationInFlight requires a non-empty workspace root path.');
|
|
2888
|
+
}
|
|
2889
|
+
if (typeof operationId !== 'string' || !HEX16_RE.test(operationId)) {
|
|
2890
|
+
throw new Error('reserveOperationInFlight requires a valid 16-char lowercase hex operationId.');
|
|
2891
|
+
}
|
|
2892
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
2893
|
+
throw new Error(`reserveOperationInFlight: invalid nowIso timestamp "${nowIso}".`);
|
|
2894
|
+
}
|
|
2895
|
+
if (typeof force !== 'boolean') {
|
|
2896
|
+
throw new Error('reserveOperationInFlight: force must be an explicit boolean.');
|
|
2897
|
+
}
|
|
2898
|
+
|
|
2899
|
+
const approvalCheck = verifyPlanApproval(approvedPlan, { nowIso, maxApprovalAgeMs });
|
|
2900
|
+
if (!approvalCheck.valid) {
|
|
2901
|
+
throw new Error(`Approved plan verification failed (${approvalCheck.code}): ${approvalCheck.errors.join('; ')}`);
|
|
2902
|
+
}
|
|
2903
|
+
|
|
2904
|
+
const matchingOps = approvedPlan.operations.filter(o => o.operation_id === operationId);
|
|
2905
|
+
if (matchingOps.length === 0) {
|
|
2906
|
+
throw new Error(`Operation "${operationId}" does not exist in approved plan "${approvedPlan.plan_id}".`);
|
|
2907
|
+
}
|
|
2908
|
+
if (matchingOps.length > 1) {
|
|
2909
|
+
throw new Error(`Duplicate operation_id "${operationId}" detected in approved plan.`);
|
|
2910
|
+
}
|
|
2911
|
+
const op = matchingOps[0];
|
|
2912
|
+
if (op.action === 'skip_unchanged') {
|
|
2913
|
+
throw new Error(`Operation "${operationId}" has action "skip_unchanged" and cannot be reserved in_flight.`);
|
|
2914
|
+
}
|
|
2915
|
+
|
|
2916
|
+
return withSyncStateLock(root, { home, nowIso }, () => {
|
|
2917
|
+
const loaded = loadSyncState(root, { home });
|
|
2918
|
+
const integrity = verifySyncStateIntegrity(loaded.state, { nowIso, maxFutureSkewMs });
|
|
2919
|
+
if (!integrity.valid) {
|
|
2920
|
+
throw new Error(`Sync-state integrity check failed: ${integrity.errors.join('; ')}`);
|
|
2921
|
+
}
|
|
2922
|
+
|
|
2923
|
+
const stateKey = makeSyncStateKey(op.database, op.canonical_key);
|
|
2924
|
+
const currentEntry = loaded.state.records[stateKey] || null;
|
|
2925
|
+
|
|
2926
|
+
// Cross-key page_id & operation_id collision checks against all other sync-state records
|
|
2927
|
+
const opNormPageId = op.existing_page_id ? normalizeNotionUuid(op.existing_page_id) : null;
|
|
2928
|
+
for (const [otherKey, otherEntry] of Object.entries(loaded.state.records)) {
|
|
2929
|
+
if (otherKey === stateKey) continue;
|
|
2930
|
+
if (opNormPageId && otherEntry.page_id && normalizeNotionUuid(otherEntry.page_id) === opNormPageId) {
|
|
2931
|
+
throw new Error(`Plan drift/conflict: page_id "${opNormPageId}" is already owned by "${otherKey}".`);
|
|
2932
|
+
}
|
|
2933
|
+
if (otherEntry.state === 'in_flight' && otherEntry.operation_id === op.operation_id) {
|
|
2934
|
+
throw new Error(`Duplicate active operation_id "${op.operation_id}" already in_flight under "${otherKey}".`);
|
|
2935
|
+
}
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
const transition = validateSyncStateTransition(currentEntry, 'in_flight', {
|
|
2939
|
+
op,
|
|
2940
|
+
nowIso,
|
|
2941
|
+
force,
|
|
2942
|
+
maxRetries,
|
|
2943
|
+
});
|
|
2944
|
+
if (!transition.valid) {
|
|
2945
|
+
throw new Error(`Cannot reserve "${stateKey}" in_flight (${transition.code}): ${transition.reason}`);
|
|
2946
|
+
}
|
|
2947
|
+
|
|
2948
|
+
const resolvedPageId = op.action === 'update'
|
|
2949
|
+
? opNormPageId
|
|
2950
|
+
: null;
|
|
2951
|
+
|
|
2952
|
+
const nextEntry = {
|
|
2953
|
+
database: op.database,
|
|
2954
|
+
canonical_key: op.canonical_key,
|
|
2955
|
+
state: 'in_flight',
|
|
2956
|
+
page_id: resolvedPageId,
|
|
2957
|
+
last_synced_hash: currentEntry?.last_synced_hash ?? null,
|
|
2958
|
+
attempted_hash: op.sync_hash,
|
|
2959
|
+
attempted_at: nowIso,
|
|
2960
|
+
last_synced_at: currentEntry?.last_synced_at ?? null,
|
|
2961
|
+
operation_id: op.operation_id,
|
|
2962
|
+
approved_plan_hash: approvedPlan.plan_hash,
|
|
2963
|
+
retry_count: Number.isInteger(currentEntry?.retry_count) ? currentEntry.retry_count : 0,
|
|
2964
|
+
next_retry_after: null,
|
|
2965
|
+
last_error: null,
|
|
2966
|
+
};
|
|
2967
|
+
|
|
2968
|
+
const nextStateDoc = {
|
|
2969
|
+
schema_version: '1.0',
|
|
2970
|
+
updated_at: nowIso,
|
|
2971
|
+
records: {
|
|
2972
|
+
...loaded.state.records,
|
|
2973
|
+
[stateKey]: nextEntry,
|
|
2974
|
+
},
|
|
2975
|
+
};
|
|
2976
|
+
|
|
2977
|
+
const nextIntegrity = verifySyncStateIntegrity(nextStateDoc, { nowIso, maxFutureSkewMs });
|
|
2978
|
+
if (!nextIntegrity.valid) {
|
|
2979
|
+
throw new Error(`Refusing to persist invalid post-reservation sync state: ${nextIntegrity.errors.join('; ')}`);
|
|
2980
|
+
}
|
|
2981
|
+
|
|
2982
|
+
const saved = saveSyncState(root, nextStateDoc, { home, nowIso });
|
|
2983
|
+
return {
|
|
2984
|
+
reserved: true,
|
|
2985
|
+
state_key: stateKey,
|
|
2986
|
+
database: op.database,
|
|
2987
|
+
canonical_key: op.canonical_key,
|
|
2988
|
+
action: op.action,
|
|
2989
|
+
operation_id: op.operation_id,
|
|
2990
|
+
approved_plan_hash: approvedPlan.plan_hash,
|
|
2991
|
+
attempted_hash: op.sync_hash,
|
|
2992
|
+
attempted_at: nowIso,
|
|
2993
|
+
existing_page_id: resolvedPageId,
|
|
2994
|
+
previous_state: currentEntry?.state ?? null,
|
|
2995
|
+
force_applied: Boolean(force && currentEntry?.state === 'failed_retryable'),
|
|
2996
|
+
path: saved.path,
|
|
2997
|
+
state: saved.state,
|
|
2998
|
+
};
|
|
2999
|
+
});
|
|
3000
|
+
}
|
|
3001
|
+
|
|
3002
|
+
// D5: Transition stale in_flight records ONLY to receipt_uncertain (never pending_sync or failed_retryable).
|
|
3003
|
+
export function expireStaleInFlightRecords(root, {
|
|
3004
|
+
nowIso = new Date().toISOString(),
|
|
3005
|
+
staleTimeoutMs = DEFAULT_STALE_IN_FLIGHT_TIMEOUT_MS,
|
|
3006
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
3007
|
+
home = os.homedir(),
|
|
3008
|
+
} = {}) {
|
|
3009
|
+
if (!isNonEmptyString(root)) {
|
|
3010
|
+
throw new Error('expireStaleInFlightRecords requires a non-empty workspace root path.');
|
|
3011
|
+
}
|
|
3012
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
3013
|
+
throw new Error(`expireStaleInFlightRecords: invalid nowIso timestamp "${nowIso}".`);
|
|
3014
|
+
}
|
|
3015
|
+
if (!Number.isSafeInteger(staleTimeoutMs) || staleTimeoutMs <= 0) {
|
|
3016
|
+
throw new Error('expireStaleInFlightRecords: staleTimeoutMs must be a positive safe integer.');
|
|
3017
|
+
}
|
|
3018
|
+
|
|
3019
|
+
return withSyncStateLock(root, { home, nowIso }, () => {
|
|
3020
|
+
const loaded = loadSyncState(root, { home });
|
|
3021
|
+
if (!loaded.exists) {
|
|
3022
|
+
return {
|
|
3023
|
+
expired_count: 0,
|
|
3024
|
+
expired_keys: [],
|
|
3025
|
+
path: loaded.path,
|
|
3026
|
+
state: loaded.state,
|
|
3027
|
+
};
|
|
3028
|
+
}
|
|
3029
|
+
|
|
3030
|
+
const integrity = verifySyncStateIntegrity(loaded.state, { nowIso, maxFutureSkewMs });
|
|
3031
|
+
if (!integrity.valid) {
|
|
3032
|
+
throw new Error(`Sync-state integrity check failed: ${integrity.errors.join('; ')}`);
|
|
3033
|
+
}
|
|
3034
|
+
|
|
3035
|
+
const nextRecords = { ...loaded.state.records };
|
|
3036
|
+
const expiredKeys = [];
|
|
3037
|
+
const sortedKeys = Object.keys(loaded.state.records).sort(codePointCompare);
|
|
3038
|
+
|
|
3039
|
+
for (const key of sortedKeys) {
|
|
3040
|
+
const entry = loaded.state.records[key];
|
|
3041
|
+
if (entry.state !== 'in_flight') continue;
|
|
3042
|
+
const check = validateSyncStateTransition(entry, 'receipt_uncertain', { nowIso, staleTimeoutMs });
|
|
3043
|
+
if (!check.valid) continue;
|
|
3044
|
+
nextRecords[key] = {
|
|
3045
|
+
...entry,
|
|
3046
|
+
state: 'receipt_uncertain',
|
|
3047
|
+
last_error: 'stale_in_flight_timeout',
|
|
3048
|
+
};
|
|
3049
|
+
expiredKeys.push(key);
|
|
3050
|
+
}
|
|
3051
|
+
|
|
3052
|
+
if (expiredKeys.length === 0) {
|
|
3053
|
+
return {
|
|
3054
|
+
expired_count: 0,
|
|
3055
|
+
expired_keys: [],
|
|
3056
|
+
path: loaded.path,
|
|
3057
|
+
state: loaded.state,
|
|
3058
|
+
};
|
|
3059
|
+
}
|
|
3060
|
+
|
|
3061
|
+
const saved = saveSyncState(root, {
|
|
3062
|
+
schema_version: '1.0',
|
|
3063
|
+
updated_at: nowIso,
|
|
3064
|
+
records: nextRecords,
|
|
3065
|
+
}, { home, nowIso });
|
|
3066
|
+
|
|
3067
|
+
return {
|
|
3068
|
+
expired_count: expiredKeys.length,
|
|
3069
|
+
expired_keys: expiredKeys,
|
|
3070
|
+
path: saved.path,
|
|
3071
|
+
state: saved.state,
|
|
3072
|
+
};
|
|
3073
|
+
});
|
|
3074
|
+
}
|
|
3075
|
+
|
|
3076
|
+
// Strictly read-only recovery inspection (D3, D4, D5). Never writes disk or mutates input.
|
|
3077
|
+
export function inspectSyncStateRecovery(stateDoc, {
|
|
3078
|
+
nowIso = new Date().toISOString(),
|
|
3079
|
+
staleTimeoutMs = DEFAULT_STALE_IN_FLIGHT_TIMEOUT_MS,
|
|
3080
|
+
maxRetries = DEFAULT_MAX_RETRIES,
|
|
3081
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
3082
|
+
} = {}) {
|
|
3083
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
3084
|
+
throw new Error(`inspectSyncStateRecovery: invalid nowIso timestamp "${nowIso}".`);
|
|
3085
|
+
}
|
|
3086
|
+
if (!Number.isSafeInteger(staleTimeoutMs) || staleTimeoutMs <= 0) {
|
|
3087
|
+
throw new Error('inspectSyncStateRecovery: staleTimeoutMs must be a positive safe integer.');
|
|
3088
|
+
}
|
|
3089
|
+
if (!Number.isSafeInteger(maxRetries) || maxRetries < 1) {
|
|
3090
|
+
throw new Error('inspectSyncStateRecovery: maxRetries must be a positive safe integer.');
|
|
3091
|
+
}
|
|
3092
|
+
|
|
3093
|
+
const integrity = verifySyncStateIntegrity(stateDoc, { nowIso, maxFutureSkewMs });
|
|
3094
|
+
if (!integrity.valid) {
|
|
3095
|
+
throw new Error(`Sync-state integrity check failed: ${integrity.errors.join('; ')}`);
|
|
3096
|
+
}
|
|
3097
|
+
|
|
3098
|
+
const nowMs = Date.parse(nowIso);
|
|
3099
|
+
const counts = {
|
|
3100
|
+
stale_in_flight: 0,
|
|
3101
|
+
active_in_flight: 0,
|
|
3102
|
+
receipt_uncertain: 0,
|
|
3103
|
+
conflict_duplicate_remote: 0,
|
|
3104
|
+
failed_retryable_ready: 0,
|
|
3105
|
+
failed_retryable_cooldown: 0,
|
|
3106
|
+
failed_retryable_cap_reached: 0,
|
|
3107
|
+
failed_permanent: 0,
|
|
3108
|
+
healthy_or_pending: 0,
|
|
3109
|
+
};
|
|
3110
|
+
const items = [];
|
|
3111
|
+
const sortedKeys = Object.keys(stateDoc.records).sort(codePointCompare);
|
|
3112
|
+
|
|
3113
|
+
for (const key of sortedKeys) {
|
|
3114
|
+
const entry = stateDoc.records[key];
|
|
3115
|
+
let classification = 'healthy_or_pending';
|
|
3116
|
+
let recommendedAction = 'none';
|
|
3117
|
+
let forceEligible = false;
|
|
3118
|
+
let ageMs = null;
|
|
3119
|
+
|
|
3120
|
+
if (entry.state === 'in_flight') {
|
|
3121
|
+
ageMs = nowMs - Date.parse(entry.attempted_at);
|
|
3122
|
+
if (ageMs >= staleTimeoutMs) {
|
|
3123
|
+
classification = 'stale_in_flight';
|
|
3124
|
+
recommendedAction = 'expire_to_receipt_uncertain_then_reconcile';
|
|
3125
|
+
} else {
|
|
3126
|
+
classification = 'active_in_flight';
|
|
3127
|
+
recommendedAction = 'wait_or_reconcile';
|
|
3128
|
+
}
|
|
3129
|
+
} else if (entry.state === 'receipt_uncertain') {
|
|
3130
|
+
classification = 'receipt_uncertain';
|
|
3131
|
+
recommendedAction = 'reconcile_remote';
|
|
3132
|
+
} else if (entry.state === 'conflict_duplicate_remote') {
|
|
3133
|
+
classification = 'conflict_duplicate_remote';
|
|
3134
|
+
recommendedAction = 'deduplicate_remote_pages_then_reconcile';
|
|
3135
|
+
} else if (entry.state === 'failed_retryable') {
|
|
3136
|
+
const retryCount = Number.isInteger(entry.retry_count) ? entry.retry_count : 0;
|
|
3137
|
+
const inCooldown = Boolean(entry.next_retry_after && nowMs < Date.parse(entry.next_retry_after));
|
|
3138
|
+
forceEligible = true;
|
|
3139
|
+
if (retryCount >= maxRetries) {
|
|
3140
|
+
classification = 'failed_retryable_cap_reached';
|
|
3141
|
+
recommendedAction = 'retry_cap_reached_requires_force_or_review';
|
|
3142
|
+
} else if (inCooldown) {
|
|
3143
|
+
classification = 'failed_retryable_cooldown';
|
|
3144
|
+
recommendedAction = 'wait_for_cooldown_or_force_retry';
|
|
3145
|
+
} else {
|
|
3146
|
+
classification = 'failed_retryable_ready';
|
|
3147
|
+
recommendedAction = 'eligible_for_new_approved_retry';
|
|
3148
|
+
}
|
|
3149
|
+
} else if (entry.state === 'failed_permanent') {
|
|
3150
|
+
classification = 'failed_permanent';
|
|
3151
|
+
recommendedAction = 'manual_remediation_and_explicit_reset';
|
|
3152
|
+
}
|
|
3153
|
+
|
|
3154
|
+
counts[classification] += 1;
|
|
3155
|
+
items.push({
|
|
3156
|
+
state_key: key,
|
|
3157
|
+
database: entry.database,
|
|
3158
|
+
canonical_key: entry.canonical_key,
|
|
3159
|
+
state: entry.state,
|
|
3160
|
+
classification,
|
|
3161
|
+
recommended_action: recommendedAction,
|
|
3162
|
+
force_eligible: forceEligible,
|
|
3163
|
+
age_ms: ageMs,
|
|
3164
|
+
retry_count: Number.isInteger(entry.retry_count) ? entry.retry_count : 0,
|
|
3165
|
+
next_retry_after: entry.next_retry_after ?? null,
|
|
3166
|
+
page_id: entry.page_id ? normalizeNotionUuid(entry.page_id) : null,
|
|
3167
|
+
operation_id: entry.operation_id ?? null,
|
|
3168
|
+
});
|
|
3169
|
+
}
|
|
3170
|
+
|
|
3171
|
+
const requiresAttention = (
|
|
3172
|
+
counts.stale_in_flight +
|
|
3173
|
+
counts.active_in_flight +
|
|
3174
|
+
counts.receipt_uncertain +
|
|
3175
|
+
counts.conflict_duplicate_remote +
|
|
3176
|
+
counts.failed_retryable_ready +
|
|
3177
|
+
counts.failed_retryable_cooldown +
|
|
3178
|
+
counts.failed_retryable_cap_reached +
|
|
3179
|
+
counts.failed_permanent
|
|
3180
|
+
) > 0;
|
|
3181
|
+
|
|
3182
|
+
return {
|
|
3183
|
+
inspected_at: nowIso,
|
|
3184
|
+
total_records: sortedKeys.length,
|
|
3185
|
+
counts,
|
|
3186
|
+
items,
|
|
3187
|
+
requires_attention: requiresAttention,
|
|
3188
|
+
};
|
|
3189
|
+
}
|
|
3190
|
+
|
|
3191
|
+
// ---------------- Stage 3 (T8-C): Receipt Verification, Failure/Backoff, Reconciliation & Explicit Reset ----------------
|
|
3192
|
+
|
|
3193
|
+
export const DEFAULT_BASE_BACKOFF_SECONDS = 60;
|
|
3194
|
+
export const DEFAULT_MAX_BACKOFF_SECONDS = 3600;
|
|
3195
|
+
|
|
3196
|
+
export const RETRYABLE_FAILURE_CODES = Object.freeze([
|
|
3197
|
+
'rate_limited',
|
|
3198
|
+
'service_unavailable',
|
|
3199
|
+
'conflict_retryable',
|
|
3200
|
+
'transient_upstream',
|
|
3201
|
+
]);
|
|
3202
|
+
const RETRYABLE_FAILURE_SET = new Set(RETRYABLE_FAILURE_CODES);
|
|
3203
|
+
|
|
3204
|
+
export const PERMANENT_FAILURE_CODES = Object.freeze([
|
|
3205
|
+
'schema_mismatch',
|
|
3206
|
+
'validation_error',
|
|
3207
|
+
'permission_denied',
|
|
3208
|
+
'invalid_database',
|
|
3209
|
+
'object_not_found',
|
|
3210
|
+
'payload_rejected',
|
|
3211
|
+
]);
|
|
3212
|
+
const PERMANENT_FAILURE_SET = new Set(PERMANENT_FAILURE_CODES);
|
|
3213
|
+
|
|
3214
|
+
export const AMBIGUOUS_FAILURE_CODES = Object.freeze([
|
|
3215
|
+
'timeout',
|
|
3216
|
+
'network_drop',
|
|
3217
|
+
'bad_gateway',
|
|
3218
|
+
'gateway_timeout',
|
|
3219
|
+
'unknown_outcome',
|
|
3220
|
+
'ambiguous_response',
|
|
3221
|
+
]);
|
|
3222
|
+
const AMBIGUOUS_FAILURE_SET = new Set(AMBIGUOUS_FAILURE_CODES);
|
|
3223
|
+
|
|
3224
|
+
const RECEIPT_TRUST_NOTE =
|
|
3225
|
+
'Structured MCP workflow evidence (not independent cryptographic proof of Notion execution); reconcile remotely whenever execution outcome or evidence authenticity is uncertain.';
|
|
3226
|
+
|
|
3227
|
+
function sanitizeSafeErrorText(raw, fallbackCode = 'sync_error') {
|
|
3228
|
+
const safeFallback = typeof fallbackCode === 'string' && /^[a-z0-9_.:-]{1,80}$/i.test(fallbackCode)
|
|
3229
|
+
? fallbackCode.toLowerCase()
|
|
3230
|
+
: 'sync_error';
|
|
3231
|
+
if (typeof raw !== 'string') return safeFallback;
|
|
3232
|
+
const cleaned = raw.replace(/[\r\n\t\x00-\x1f\x7f]+/g, ' ').replace(/\s{2,}/g, ' ').trim();
|
|
3233
|
+
if (!cleaned) return safeFallback;
|
|
3234
|
+
if (hasDisallowedLastErrorContent(cleaned) || PHONE_PATTERNS.some(re => re.test(cleaned))) {
|
|
3235
|
+
return safeFallback;
|
|
3236
|
+
}
|
|
3237
|
+
return cleaned.length <= 120 ? cleaned : `${cleaned.slice(0, 117).trimEnd()}...`;
|
|
3238
|
+
}
|
|
3239
|
+
|
|
3240
|
+
function findCrossKeyPageCollision(records, targetStateKey, normPageId) {
|
|
3241
|
+
if (!normPageId) return null;
|
|
3242
|
+
const sortedKeys = Object.keys(records).sort(codePointCompare);
|
|
3243
|
+
for (const otherKey of sortedKeys) {
|
|
3244
|
+
if (otherKey === targetStateKey) continue;
|
|
3245
|
+
const other = records[otherKey];
|
|
3246
|
+
if (other?.page_id && normalizeNotionUuid(other.page_id) === normPageId) {
|
|
3247
|
+
return otherKey;
|
|
3248
|
+
}
|
|
3249
|
+
if (Array.isArray(other?.conflicting_page_ids)) {
|
|
3250
|
+
for (const cid of other.conflicting_page_ids) {
|
|
3251
|
+
if (normalizeNotionUuid(cid) === normPageId) {
|
|
3252
|
+
return otherKey;
|
|
3253
|
+
}
|
|
3254
|
+
}
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
return null;
|
|
3258
|
+
}
|
|
3259
|
+
|
|
3260
|
+
// Safety Resolution 1: Validate structured MCP execution receipt + read-back properties.
|
|
3261
|
+
// Structured evidence is NOT cryptographic proof; any mismatch/omission fails closed.
|
|
3262
|
+
export function verifySyncReceiptEvidence(inFlightEntry, receipt, {
|
|
3263
|
+
expectedDatabaseId = null,
|
|
3264
|
+
nowIso = null,
|
|
3265
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
3266
|
+
} = {}) {
|
|
3267
|
+
const errors = [];
|
|
3268
|
+
let code = null;
|
|
3269
|
+
const setErr = (errCode, msg) => {
|
|
3270
|
+
if (code === null) code = errCode;
|
|
3271
|
+
errors.push(msg);
|
|
3272
|
+
};
|
|
3273
|
+
|
|
3274
|
+
if (!isObj(inFlightEntry) || inFlightEntry.state !== 'in_flight') {
|
|
3275
|
+
setErr('entry_not_in_flight', 'Receipt verification requires an active in_flight sync-state entry.');
|
|
3276
|
+
return { valid: false, verified_page_id: null, verified_at: null, code, errors, trust_note: RECEIPT_TRUST_NOTE };
|
|
3277
|
+
}
|
|
3278
|
+
if (
|
|
3279
|
+
!TARGET_DATABASE_SET.has(inFlightEntry.database) ||
|
|
3280
|
+
!isNonEmptyString(inFlightEntry.canonical_key) ||
|
|
3281
|
+
typeof inFlightEntry.operation_id !== 'string' || !HEX16_RE.test(inFlightEntry.operation_id) ||
|
|
3282
|
+
typeof inFlightEntry.approved_plan_hash !== 'string' || !HEX64_RE.test(inFlightEntry.approved_plan_hash) ||
|
|
3283
|
+
typeof inFlightEntry.attempted_hash !== 'string' || !HEX16_RE.test(inFlightEntry.attempted_hash) ||
|
|
3284
|
+
!isValidIsoDateTime(inFlightEntry.attempted_at)
|
|
3285
|
+
) {
|
|
3286
|
+
setErr('invalid_in_flight_entry', 'in_flight sync-state entry is missing required binding metadata.');
|
|
3287
|
+
return { valid: false, verified_page_id: null, verified_at: null, code, errors, trust_note: RECEIPT_TRUST_NOTE };
|
|
3288
|
+
}
|
|
3289
|
+
if (nowIso !== null && !isValidIsoDateTime(nowIso)) {
|
|
3290
|
+
setErr('invalid_now_iso', `verifySyncReceiptEvidence: invalid nowIso timestamp "${nowIso}".`);
|
|
3291
|
+
}
|
|
3292
|
+
if (!Number.isSafeInteger(maxFutureSkewMs) || maxFutureSkewMs < 0) {
|
|
3293
|
+
setErr('invalid_future_skew', 'verifySyncReceiptEvidence: maxFutureSkewMs must be a non-negative safe integer.');
|
|
3294
|
+
}
|
|
3295
|
+
|
|
3296
|
+
let expectedNormDbId = null;
|
|
3297
|
+
if (expectedDatabaseId !== null) {
|
|
3298
|
+
expectedNormDbId = normalizeNotionUuid(expectedDatabaseId);
|
|
3299
|
+
if (!expectedNormDbId) {
|
|
3300
|
+
setErr('invalid_expected_database_id', 'expectedDatabaseId must be a valid Notion UUID or null.');
|
|
3301
|
+
}
|
|
3302
|
+
}
|
|
3303
|
+
|
|
3304
|
+
if (!isObj(receipt)) {
|
|
3305
|
+
setErr('missing_or_invalid_receipt', 'Structured mcp_evidence receipt must be a JSON object.');
|
|
3306
|
+
return { valid: false, verified_page_id: null, verified_at: null, code, errors, trust_note: RECEIPT_TRUST_NOTE };
|
|
3307
|
+
}
|
|
3308
|
+
|
|
3309
|
+
if (receipt.operation_id !== inFlightEntry.operation_id) {
|
|
3310
|
+
setErr('receipt_operation_id_mismatch', 'Receipt operation_id does not match active in_flight reservation.');
|
|
3311
|
+
}
|
|
3312
|
+
if (receipt.approved_plan_hash !== inFlightEntry.approved_plan_hash) {
|
|
3313
|
+
setErr('receipt_plan_hash_mismatch', 'Receipt approved_plan_hash does not match active in_flight reservation.');
|
|
3314
|
+
}
|
|
3315
|
+
if (receipt.database !== inFlightEntry.database || receipt.canonical_key !== inFlightEntry.canonical_key) {
|
|
3316
|
+
setErr('receipt_target_mismatch', 'Receipt database/canonical_key does not match active in_flight reservation.');
|
|
3317
|
+
}
|
|
3318
|
+
if (receipt.sync_hash !== inFlightEntry.attempted_hash) {
|
|
3319
|
+
setErr('receipt_sync_hash_mismatch', 'Receipt sync_hash does not match active in_flight attempted_hash.');
|
|
3320
|
+
}
|
|
3321
|
+
if (receipt.archived === true || receipt.in_trash === true) {
|
|
3322
|
+
setErr('receipt_page_archived_or_trashed', 'Receipt indicates target Notion page is archived or in_trash.');
|
|
3323
|
+
}
|
|
3324
|
+
|
|
3325
|
+
const verifiedPageId = normalizeNotionUuid(receipt.page_id);
|
|
3326
|
+
if (!verifiedPageId) {
|
|
3327
|
+
setErr('invalid_receipt_page_id', 'Receipt page_id must be a valid Notion UUID.');
|
|
3328
|
+
} else if (inFlightEntry.page_id !== undefined && inFlightEntry.page_id !== null) {
|
|
3329
|
+
const expectedPageId = normalizeNotionUuid(inFlightEntry.page_id);
|
|
3330
|
+
if (expectedPageId && verifiedPageId !== expectedPageId) {
|
|
3331
|
+
setErr('receipt_page_id_mismatch', `Receipt page_id "${verifiedPageId}" contradicts reserved update page_id "${expectedPageId}".`);
|
|
3332
|
+
}
|
|
3333
|
+
}
|
|
3334
|
+
|
|
3335
|
+
const receiptDbId = normalizeNotionUuid(receipt.database_id);
|
|
3336
|
+
if (!receiptDbId) {
|
|
3337
|
+
setErr('invalid_receipt_database_id', 'Receipt database_id must be a valid Notion UUID.');
|
|
3338
|
+
} else if (expectedNormDbId && receiptDbId !== expectedNormDbId) {
|
|
3339
|
+
setErr('receipt_database_id_mismatch', `Receipt database_id "${receiptDbId}" does not match expectedDatabaseId "${expectedNormDbId}".`);
|
|
3340
|
+
}
|
|
3341
|
+
|
|
3342
|
+
let verifiedAt = null;
|
|
3343
|
+
if (!isValidIsoDateTime(receipt.verified_at)) {
|
|
3344
|
+
setErr('invalid_receipt_verified_at', 'Receipt verified_at must be a valid ISO-8601 date-time.');
|
|
3345
|
+
} else {
|
|
3346
|
+
verifiedAt = receipt.verified_at;
|
|
3347
|
+
if (Date.parse(verifiedAt) < Date.parse(inFlightEntry.attempted_at)) {
|
|
3348
|
+
setErr('receipt_predates_attempt', `Receipt verified_at "${verifiedAt}" predates in_flight attempted_at "${inFlightEntry.attempted_at}".`);
|
|
3349
|
+
}
|
|
3350
|
+
if (nowIso !== null && isValidIsoDateTime(nowIso) && Number.isSafeInteger(maxFutureSkewMs) && maxFutureSkewMs >= 0) {
|
|
3351
|
+
if (Date.parse(verifiedAt) - Date.parse(nowIso) > maxFutureSkewMs) {
|
|
3352
|
+
setErr('receipt_verified_at_in_future', `Receipt verified_at "${verifiedAt}" is in the future beyond allowed skew (${maxFutureSkewMs}ms).`);
|
|
3353
|
+
}
|
|
3354
|
+
}
|
|
3355
|
+
}
|
|
3356
|
+
|
|
3357
|
+
// Mandatory read-back verification of canonical key property & Sync Hash
|
|
3358
|
+
const expectedFilterProp = RECONCILE_FILTER_PROPERTY_BY_DB[inFlightEntry.database];
|
|
3359
|
+
if (!isObj(receipt.readback_properties)) {
|
|
3360
|
+
setErr('missing_readback_properties', 'Receipt requires readback_properties confirming persisted canonical key and Sync Hash.');
|
|
3361
|
+
} else {
|
|
3362
|
+
if (receipt.readback_properties[expectedFilterProp] !== inFlightEntry.canonical_key) {
|
|
3363
|
+
setErr('readback_canonical_key_mismatch', `Read-back property "${expectedFilterProp}" does not match canonical_key "${inFlightEntry.canonical_key}".`);
|
|
3364
|
+
}
|
|
3365
|
+
if (receipt.readback_properties['Sync Hash'] !== inFlightEntry.attempted_hash) {
|
|
3366
|
+
setErr('readback_sync_hash_mismatch', 'Read-back "Sync Hash" does not match active in_flight attempted_hash.');
|
|
3367
|
+
}
|
|
3368
|
+
}
|
|
3369
|
+
|
|
3370
|
+
return {
|
|
3371
|
+
valid: errors.length === 0,
|
|
3372
|
+
verified_page_id: errors.length === 0 ? verifiedPageId : null,
|
|
3373
|
+
verified_at: errors.length === 0 ? verifiedAt : null,
|
|
3374
|
+
code,
|
|
3375
|
+
errors,
|
|
3376
|
+
trust_note: RECEIPT_TRUST_NOTE,
|
|
3377
|
+
};
|
|
3378
|
+
}
|
|
3379
|
+
|
|
3380
|
+
// Apply structured receipt under exclusive lock:
|
|
3381
|
+
// - Valid operation-bound evidence + read-back -> synced
|
|
3382
|
+
// - Incomplete/mismatched/colliding evidence -> receipt_uncertain (fail closed)
|
|
3383
|
+
export function applySyncReceipt(root, {
|
|
3384
|
+
database,
|
|
3385
|
+
canonicalKey,
|
|
3386
|
+
operationId,
|
|
3387
|
+
approvedPlanHash,
|
|
3388
|
+
receipt,
|
|
3389
|
+
expectedDatabaseId = null,
|
|
3390
|
+
nowIso = new Date().toISOString(),
|
|
3391
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
3392
|
+
home = os.homedir(),
|
|
3393
|
+
} = {}) {
|
|
3394
|
+
if (!isNonEmptyString(root)) {
|
|
3395
|
+
throw new Error('applySyncReceipt requires a non-empty workspace root path.');
|
|
3396
|
+
}
|
|
3397
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
3398
|
+
throw new Error(`applySyncReceipt: invalid database "${database}".`);
|
|
3399
|
+
}
|
|
3400
|
+
if (!isNonEmptyString(canonicalKey)) {
|
|
3401
|
+
throw new Error('applySyncReceipt requires a non-empty canonicalKey.');
|
|
3402
|
+
}
|
|
3403
|
+
if (typeof operationId !== 'string' || !HEX16_RE.test(operationId)) {
|
|
3404
|
+
throw new Error('applySyncReceipt requires a valid 16-char lowercase hex operationId.');
|
|
3405
|
+
}
|
|
3406
|
+
if (typeof approvedPlanHash !== 'string' || !HEX64_RE.test(approvedPlanHash)) {
|
|
3407
|
+
throw new Error('applySyncReceipt requires a valid 64-char lowercase hex approvedPlanHash.');
|
|
3408
|
+
}
|
|
3409
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
3410
|
+
throw new Error(`applySyncReceipt: invalid nowIso timestamp "${nowIso}".`);
|
|
3411
|
+
}
|
|
3412
|
+
if (expectedDatabaseId !== null && normalizeNotionUuid(expectedDatabaseId) === null) {
|
|
3413
|
+
throw new Error('applySyncReceipt: expectedDatabaseId must be a valid Notion UUID or null.');
|
|
3414
|
+
}
|
|
3415
|
+
|
|
3416
|
+
return withSyncStateLock(root, { home, nowIso }, () => {
|
|
3417
|
+
const loaded = loadSyncState(root, { home });
|
|
3418
|
+
if (!loaded.exists) {
|
|
3419
|
+
throw new Error('applySyncReceipt: logs/sync-state.json does not exist; no active in_flight reservation found.');
|
|
3420
|
+
}
|
|
3421
|
+
const integrity = verifySyncStateIntegrity(loaded.state, { nowIso, maxFutureSkewMs });
|
|
3422
|
+
if (!integrity.valid) {
|
|
3423
|
+
throw new Error(`Sync-state integrity check failed: ${integrity.errors.join('; ')}`);
|
|
3424
|
+
}
|
|
3425
|
+
|
|
3426
|
+
const stateKey = makeSyncStateKey(database, canonicalKey);
|
|
3427
|
+
const entry = loaded.state.records[stateKey];
|
|
3428
|
+
if (!entry || entry.state !== 'in_flight') {
|
|
3429
|
+
throw new Error(`applySyncReceipt: "${stateKey}" is not in_flight (current state: "${entry?.state ?? 'none'}").`);
|
|
3430
|
+
}
|
|
3431
|
+
if (entry.operation_id !== operationId) {
|
|
3432
|
+
throw new Error(`applySyncReceipt: operationId "${operationId}" does not match active in_flight operation_id "${entry.operation_id}".`);
|
|
3433
|
+
}
|
|
3434
|
+
if (entry.approved_plan_hash !== approvedPlanHash) {
|
|
3435
|
+
throw new Error('applySyncReceipt: approvedPlanHash does not match active in_flight reservation.');
|
|
3436
|
+
}
|
|
3437
|
+
|
|
3438
|
+
const check = verifySyncReceiptEvidence(entry, receipt, { expectedDatabaseId, nowIso, maxFutureSkewMs });
|
|
3439
|
+
let nextEntry;
|
|
3440
|
+
let applied = false;
|
|
3441
|
+
let resultCode = check.code;
|
|
3442
|
+
let resultErrors = [...check.errors];
|
|
3443
|
+
|
|
3444
|
+
if (check.valid) {
|
|
3445
|
+
const collisionKey = findCrossKeyPageCollision(loaded.state.records, stateKey, check.verified_page_id);
|
|
3446
|
+
if (collisionKey) {
|
|
3447
|
+
resultCode = 'receipt_page_id_cross_key_collision';
|
|
3448
|
+
resultErrors = [`Receipt page_id "${check.verified_page_id}" collides with existing key "${collisionKey}".`];
|
|
3449
|
+
nextEntry = {
|
|
3450
|
+
...entry,
|
|
3451
|
+
state: 'receipt_uncertain',
|
|
3452
|
+
last_error: 'receipt_page_id_cross_key_collision',
|
|
3453
|
+
};
|
|
3454
|
+
} else {
|
|
3455
|
+
applied = true;
|
|
3456
|
+
nextEntry = {
|
|
3457
|
+
database: entry.database,
|
|
3458
|
+
canonical_key: entry.canonical_key,
|
|
3459
|
+
state: 'synced',
|
|
3460
|
+
page_id: check.verified_page_id,
|
|
3461
|
+
last_synced_hash: entry.attempted_hash,
|
|
3462
|
+
attempted_hash: null,
|
|
3463
|
+
attempted_at: null,
|
|
3464
|
+
last_synced_at: check.verified_at,
|
|
3465
|
+
operation_id: null,
|
|
3466
|
+
approved_plan_hash: null,
|
|
3467
|
+
retry_count: 0,
|
|
3468
|
+
next_retry_after: null,
|
|
3469
|
+
last_error: null,
|
|
3470
|
+
};
|
|
3471
|
+
}
|
|
3472
|
+
} else {
|
|
3473
|
+
nextEntry = {
|
|
3474
|
+
...entry,
|
|
3475
|
+
state: 'receipt_uncertain',
|
|
3476
|
+
last_error: sanitizeSafeErrorText(`receipt_verification_failed:${check.code || 'invalid'}`, 'receipt_verification_failed'),
|
|
3477
|
+
};
|
|
3478
|
+
}
|
|
3479
|
+
|
|
3480
|
+
const nextStateDoc = {
|
|
3481
|
+
schema_version: '1.0',
|
|
3482
|
+
updated_at: nowIso,
|
|
3483
|
+
records: {
|
|
3484
|
+
...loaded.state.records,
|
|
3485
|
+
[stateKey]: nextEntry,
|
|
3486
|
+
},
|
|
3487
|
+
};
|
|
3488
|
+
const nextIntegrity = verifySyncStateIntegrity(nextStateDoc, { nowIso, maxFutureSkewMs });
|
|
3489
|
+
if (!nextIntegrity.valid) {
|
|
3490
|
+
throw new Error(`Refusing to persist invalid post-receipt sync state: ${nextIntegrity.errors.join('; ')}`);
|
|
3491
|
+
}
|
|
3492
|
+
|
|
3493
|
+
const saved = saveSyncState(root, nextStateDoc, { home, nowIso });
|
|
3494
|
+
return {
|
|
3495
|
+
applied,
|
|
3496
|
+
state_key: stateKey,
|
|
3497
|
+
state: nextEntry.state,
|
|
3498
|
+
page_id: applied ? nextEntry.page_id : (nextEntry.page_id ?? null),
|
|
3499
|
+
last_synced_hash: applied ? nextEntry.last_synced_hash : (nextEntry.last_synced_hash ?? null),
|
|
3500
|
+
last_synced_at: applied ? nextEntry.last_synced_at : (nextEntry.last_synced_at ?? null),
|
|
3501
|
+
code: resultCode,
|
|
3502
|
+
errors: resultErrors,
|
|
3503
|
+
trust_note: RECEIPT_TRUST_NOTE,
|
|
3504
|
+
path: saved.path,
|
|
3505
|
+
sync_state: saved.state,
|
|
3506
|
+
};
|
|
3507
|
+
});
|
|
3508
|
+
}
|
|
3509
|
+
|
|
3510
|
+
// Deterministic failure classification & exponential backoff recording (D3/D4/Safety Resolution 3):
|
|
3511
|
+
// - Ambiguous/timeout/unknown or mutationNotApplied !== true -> ALWAYS receipt_uncertain
|
|
3512
|
+
// - Confirmed non-applied retryable -> failed_retryable (stays failed_retryable at cap for --force)
|
|
3513
|
+
// - Confirmed non-applied permanent -> failed_permanent (held until explicit resetPermanentFailure)
|
|
3514
|
+
export function recordSyncFailure(root, {
|
|
3515
|
+
database,
|
|
3516
|
+
canonicalKey,
|
|
3517
|
+
operationId,
|
|
3518
|
+
approvedPlanHash,
|
|
3519
|
+
errorCode,
|
|
3520
|
+
errorMessage = null,
|
|
3521
|
+
mutationNotApplied = false,
|
|
3522
|
+
nowIso = new Date().toISOString(),
|
|
3523
|
+
baseBackoffSeconds = DEFAULT_BASE_BACKOFF_SECONDS,
|
|
3524
|
+
maxBackoffSeconds = DEFAULT_MAX_BACKOFF_SECONDS,
|
|
3525
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
3526
|
+
home = os.homedir(),
|
|
3527
|
+
} = {}) {
|
|
3528
|
+
if (!isNonEmptyString(root)) {
|
|
3529
|
+
throw new Error('recordSyncFailure requires a non-empty workspace root path.');
|
|
3530
|
+
}
|
|
3531
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
3532
|
+
throw new Error(`recordSyncFailure: invalid database "${database}".`);
|
|
3533
|
+
}
|
|
3534
|
+
if (!isNonEmptyString(canonicalKey)) {
|
|
3535
|
+
throw new Error('recordSyncFailure requires a non-empty canonicalKey.');
|
|
3536
|
+
}
|
|
3537
|
+
if (typeof operationId !== 'string' || !HEX16_RE.test(operationId)) {
|
|
3538
|
+
throw new Error('recordSyncFailure requires a valid 16-char lowercase hex operationId.');
|
|
3539
|
+
}
|
|
3540
|
+
if (typeof approvedPlanHash !== 'string' || !HEX64_RE.test(approvedPlanHash)) {
|
|
3541
|
+
throw new Error('recordSyncFailure requires a valid 64-char lowercase hex approvedPlanHash.');
|
|
3542
|
+
}
|
|
3543
|
+
if (typeof mutationNotApplied !== 'boolean') {
|
|
3544
|
+
throw new Error('recordSyncFailure: mutationNotApplied must be an explicit boolean.');
|
|
3545
|
+
}
|
|
3546
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
3547
|
+
throw new Error(`recordSyncFailure: invalid nowIso timestamp "${nowIso}".`);
|
|
3548
|
+
}
|
|
3549
|
+
if (!Number.isSafeInteger(baseBackoffSeconds) || baseBackoffSeconds <= 0) {
|
|
3550
|
+
throw new Error('recordSyncFailure: baseBackoffSeconds must be a positive safe integer.');
|
|
3551
|
+
}
|
|
3552
|
+
if (!Number.isSafeInteger(maxBackoffSeconds) || maxBackoffSeconds < baseBackoffSeconds) {
|
|
3553
|
+
throw new Error('recordSyncFailure: maxBackoffSeconds must be a safe integer >= baseBackoffSeconds.');
|
|
3554
|
+
}
|
|
3555
|
+
|
|
3556
|
+
const normCode = typeof errorCode === 'string' && errorCode.trim().length > 0
|
|
3557
|
+
? errorCode.trim().toLowerCase()
|
|
3558
|
+
: 'unknown_outcome';
|
|
3559
|
+
|
|
3560
|
+
return withSyncStateLock(root, { home, nowIso }, () => {
|
|
3561
|
+
const loaded = loadSyncState(root, { home });
|
|
3562
|
+
if (!loaded.exists) {
|
|
3563
|
+
throw new Error('recordSyncFailure: logs/sync-state.json does not exist; no active in_flight reservation found.');
|
|
3564
|
+
}
|
|
3565
|
+
const integrity = verifySyncStateIntegrity(loaded.state, { nowIso, maxFutureSkewMs });
|
|
3566
|
+
if (!integrity.valid) {
|
|
3567
|
+
throw new Error(`Sync-state integrity check failed: ${integrity.errors.join('; ')}`);
|
|
3568
|
+
}
|
|
3569
|
+
|
|
3570
|
+
const stateKey = makeSyncStateKey(database, canonicalKey);
|
|
3571
|
+
const entry = loaded.state.records[stateKey];
|
|
3572
|
+
if (!entry || entry.state !== 'in_flight') {
|
|
3573
|
+
throw new Error(`recordSyncFailure: "${stateKey}" is not in_flight (current state: "${entry?.state ?? 'none'}").`);
|
|
3574
|
+
}
|
|
3575
|
+
if (entry.operation_id !== operationId) {
|
|
3576
|
+
throw new Error(`recordSyncFailure: operationId "${operationId}" does not match active in_flight operation_id "${entry.operation_id}".`);
|
|
3577
|
+
}
|
|
3578
|
+
if (entry.approved_plan_hash !== approvedPlanHash) {
|
|
3579
|
+
throw new Error('recordSyncFailure: approvedPlanHash does not match active in_flight reservation.');
|
|
3580
|
+
}
|
|
3581
|
+
|
|
3582
|
+
const rawErrText = isNonEmptyString(errorMessage) ? `${normCode}: ${errorMessage}` : normCode;
|
|
3583
|
+
let nextEntry;
|
|
3584
|
+
let classification;
|
|
3585
|
+
|
|
3586
|
+
if (mutationNotApplied === true && RETRYABLE_FAILURE_SET.has(normCode)) {
|
|
3587
|
+
classification = 'retryable';
|
|
3588
|
+
const nextRetryCount = (Number.isInteger(entry.retry_count) ? entry.retry_count : 0) + 1;
|
|
3589
|
+
const exponent = Math.min(nextRetryCount - 1, 20);
|
|
3590
|
+
const delaySeconds = Math.min(baseBackoffSeconds * (2 ** exponent), maxBackoffSeconds);
|
|
3591
|
+
const nextRetryAfter = new Date(Date.parse(nowIso) + delaySeconds * 1000).toISOString();
|
|
3592
|
+
nextEntry = {
|
|
3593
|
+
...entry,
|
|
3594
|
+
state: 'failed_retryable',
|
|
3595
|
+
retry_count: nextRetryCount,
|
|
3596
|
+
next_retry_after: nextRetryAfter,
|
|
3597
|
+
last_error: sanitizeSafeErrorText(rawErrText, normCode),
|
|
3598
|
+
};
|
|
3599
|
+
} else if (mutationNotApplied === true && PERMANENT_FAILURE_SET.has(normCode)) {
|
|
3600
|
+
classification = 'permanent';
|
|
3601
|
+
nextEntry = {
|
|
3602
|
+
...entry,
|
|
3603
|
+
state: 'failed_permanent',
|
|
3604
|
+
next_retry_after: null,
|
|
3605
|
+
last_error: sanitizeSafeErrorText(rawErrText, normCode),
|
|
3606
|
+
};
|
|
3607
|
+
} else {
|
|
3608
|
+
// Ambiguous / timeout / network_drop / unknown OR mutationNotApplied === false -> ALWAYS receipt_uncertain
|
|
3609
|
+
classification = 'ambiguous_uncertain';
|
|
3610
|
+
const safeFallback = AMBIGUOUS_FAILURE_SET.has(normCode) ? normCode : 'ambiguous_outcome';
|
|
3611
|
+
nextEntry = {
|
|
3612
|
+
...entry,
|
|
3613
|
+
state: 'receipt_uncertain',
|
|
3614
|
+
next_retry_after: null,
|
|
3615
|
+
last_error: sanitizeSafeErrorText(rawErrText, safeFallback),
|
|
3616
|
+
};
|
|
3617
|
+
}
|
|
3618
|
+
|
|
3619
|
+
const nextStateDoc = {
|
|
3620
|
+
schema_version: '1.0',
|
|
3621
|
+
updated_at: nowIso,
|
|
3622
|
+
records: {
|
|
3623
|
+
...loaded.state.records,
|
|
3624
|
+
[stateKey]: nextEntry,
|
|
3625
|
+
},
|
|
3626
|
+
};
|
|
3627
|
+
const nextIntegrity = verifySyncStateIntegrity(nextStateDoc, { nowIso, maxFutureSkewMs });
|
|
3628
|
+
if (!nextIntegrity.valid) {
|
|
3629
|
+
throw new Error(`Refusing to persist invalid post-failure sync state: ${nextIntegrity.errors.join('; ')}`);
|
|
3630
|
+
}
|
|
3631
|
+
|
|
3632
|
+
const saved = saveSyncState(root, nextStateDoc, { home, nowIso });
|
|
3633
|
+
return {
|
|
3634
|
+
recorded: true,
|
|
3635
|
+
state_key: stateKey,
|
|
3636
|
+
previous_state: 'in_flight',
|
|
3637
|
+
classification,
|
|
3638
|
+
state: nextEntry.state,
|
|
3639
|
+
retry_count: Number.isInteger(nextEntry.retry_count) ? nextEntry.retry_count : 0,
|
|
3640
|
+
next_retry_after: nextEntry.next_retry_after ?? null,
|
|
3641
|
+
last_error: nextEntry.last_error,
|
|
3642
|
+
path: saved.path,
|
|
3643
|
+
sync_state: saved.state,
|
|
3644
|
+
};
|
|
3645
|
+
});
|
|
3646
|
+
}
|
|
3647
|
+
|
|
3648
|
+
// Safety Resolution 2: Validate all 6 minimum query-snapshot completeness invariants.
|
|
3649
|
+
// Incomplete, errored, timed-out, mis-filtered, or predating snapshots MUST fail closed.
|
|
3650
|
+
export function validateReconcileQuerySnapshot(snapshot, {
|
|
3651
|
+
expectedDatabase,
|
|
3652
|
+
expectedCanonicalKey,
|
|
3653
|
+
expectedDatabaseId,
|
|
3654
|
+
minQueriedAt = null,
|
|
3655
|
+
nowIso = null,
|
|
3656
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
3657
|
+
} = {}) {
|
|
3658
|
+
const errors = [];
|
|
3659
|
+
let code = null;
|
|
3660
|
+
const setErr = (errCode, msg) => {
|
|
3661
|
+
if (code === null) code = errCode;
|
|
3662
|
+
errors.push(msg);
|
|
3663
|
+
};
|
|
3664
|
+
|
|
3665
|
+
if (!TARGET_DATABASE_SET.has(expectedDatabase)) {
|
|
3666
|
+
setErr('invalid_expected_database', `Unknown expectedDatabase "${expectedDatabase}".`);
|
|
3667
|
+
}
|
|
3668
|
+
if (!isNonEmptyString(expectedCanonicalKey)) {
|
|
3669
|
+
setErr('invalid_expected_canonical_key', 'expectedCanonicalKey must be a non-empty string.');
|
|
3670
|
+
}
|
|
3671
|
+
const normExpectedDbId = normalizeNotionUuid(expectedDatabaseId);
|
|
3672
|
+
if (!normExpectedDbId) {
|
|
3673
|
+
setErr('invalid_expected_database_id', 'expectedDatabaseId must be a valid Notion UUID.');
|
|
3674
|
+
}
|
|
3675
|
+
if (minQueriedAt !== null && !isValidIsoDateTime(minQueriedAt)) {
|
|
3676
|
+
setErr('invalid_min_queried_at', `Invalid minQueriedAt timestamp "${minQueriedAt}".`);
|
|
3677
|
+
}
|
|
3678
|
+
if (nowIso !== null && !isValidIsoDateTime(nowIso)) {
|
|
3679
|
+
setErr('invalid_now_iso', `Invalid nowIso timestamp "${nowIso}".`);
|
|
3680
|
+
}
|
|
3681
|
+
if (!Number.isSafeInteger(maxFutureSkewMs) || maxFutureSkewMs < 0) {
|
|
3682
|
+
setErr('invalid_future_skew', 'maxFutureSkewMs must be a non-negative safe integer.');
|
|
3683
|
+
}
|
|
3684
|
+
|
|
3685
|
+
if (!isObj(snapshot)) {
|
|
3686
|
+
setErr('snapshot_not_object', 'Reconciliation query snapshot must be a JSON object.');
|
|
3687
|
+
return { valid: false, complete: false, code, errors, active_pages: [], queried_at: null };
|
|
3688
|
+
}
|
|
3689
|
+
|
|
3690
|
+
// 1. Target database & database_id
|
|
3691
|
+
if (snapshot.database !== expectedDatabase) {
|
|
3692
|
+
setErr('snapshot_database_mismatch', `Snapshot database "${snapshot.database}" does not match expected "${expectedDatabase}".`);
|
|
3693
|
+
}
|
|
3694
|
+
const snapDbId = normalizeNotionUuid(snapshot.database_id);
|
|
3695
|
+
if (!snapDbId || (normExpectedDbId && snapDbId !== normExpectedDbId)) {
|
|
3696
|
+
setErr('snapshot_database_id_mismatch', 'Snapshot database_id is invalid or does not match expectedDatabaseId.');
|
|
3697
|
+
}
|
|
3698
|
+
|
|
3699
|
+
// 2. Exact canonical filter property & value
|
|
3700
|
+
const expectedProp = TARGET_DATABASE_SET.has(expectedDatabase) ? RECONCILE_FILTER_PROPERTY_BY_DB[expectedDatabase] : null;
|
|
3701
|
+
if (snapshot.filter_property !== expectedProp) {
|
|
3702
|
+
setErr('snapshot_filter_property_mismatch', `Snapshot filter_property "${snapshot.filter_property}" must equal "${expectedProp}".`);
|
|
3703
|
+
}
|
|
3704
|
+
if (snapshot.filter_value !== expectedCanonicalKey) {
|
|
3705
|
+
setErr('snapshot_filter_value_mismatch', `Snapshot filter_value "${snapshot.filter_value}" must equal "${expectedCanonicalKey}".`);
|
|
3706
|
+
}
|
|
3707
|
+
|
|
3708
|
+
// 3. Explicit query success
|
|
3709
|
+
if (snapshot.query_succeeded !== true) {
|
|
3710
|
+
setErr('snapshot_query_failed', 'Snapshot query_succeeded must be explicitly true.');
|
|
3711
|
+
}
|
|
3712
|
+
|
|
3713
|
+
// 4. Complete pagination (zero missing pages)
|
|
3714
|
+
if (snapshot.pagination_complete !== true || snapshot.has_more !== false || snapshot.next_cursor !== null) {
|
|
3715
|
+
setErr('snapshot_pagination_incomplete', 'Snapshot pagination is incomplete (requires pagination_complete=true, has_more=false, next_cursor=null).');
|
|
3716
|
+
}
|
|
3717
|
+
|
|
3718
|
+
// 5. Zero unresolved query errors or timeouts
|
|
3719
|
+
if (snapshot.timed_out !== false) {
|
|
3720
|
+
setErr('snapshot_timed_out', 'Snapshot timed_out must be explicitly false.');
|
|
3721
|
+
}
|
|
3722
|
+
if (snapshot.errors !== undefined && snapshot.errors !== null) {
|
|
3723
|
+
if (!Array.isArray(snapshot.errors) || snapshot.errors.length > 0) {
|
|
3724
|
+
setErr('snapshot_has_errors', 'Snapshot contains unresolved query errors.');
|
|
3725
|
+
}
|
|
3726
|
+
}
|
|
3727
|
+
|
|
3728
|
+
// 6. Strict ISO-8601 queried_at + causality check
|
|
3729
|
+
let queriedAt = null;
|
|
3730
|
+
if (!isValidIsoDateTime(snapshot.queried_at)) {
|
|
3731
|
+
setErr('invalid_queried_at', 'Snapshot queried_at must be a valid ISO-8601 date-time.');
|
|
3732
|
+
} else {
|
|
3733
|
+
queriedAt = snapshot.queried_at;
|
|
3734
|
+
if (minQueriedAt !== null && isValidIsoDateTime(minQueriedAt) && Date.parse(queriedAt) < Date.parse(minQueriedAt)) {
|
|
3735
|
+
setErr('snapshot_predates_attempt', `Snapshot queried_at "${queriedAt}" predates in_flight attempted_at "${minQueriedAt}".`);
|
|
3736
|
+
}
|
|
3737
|
+
if (nowIso !== null && isValidIsoDateTime(nowIso) && Number.isSafeInteger(maxFutureSkewMs) && maxFutureSkewMs >= 0) {
|
|
3738
|
+
if (Date.parse(queriedAt) - Date.parse(nowIso) > maxFutureSkewMs) {
|
|
3739
|
+
setErr('snapshot_queried_at_in_future', `Snapshot queried_at "${queriedAt}" is in the future beyond allowed skew (${maxFutureSkewMs}ms).`);
|
|
3740
|
+
}
|
|
3741
|
+
}
|
|
3742
|
+
}
|
|
3743
|
+
|
|
3744
|
+
// Validate & deduplicate active remote pages
|
|
3745
|
+
const activePages = [];
|
|
3746
|
+
if (!Array.isArray(snapshot.pages)) {
|
|
3747
|
+
setErr('snapshot_pages_not_array', 'Snapshot pages must be an array.');
|
|
3748
|
+
} else {
|
|
3749
|
+
const seenPages = new Map();
|
|
3750
|
+
for (let i = 0; i < snapshot.pages.length; i++) {
|
|
3751
|
+
const p = snapshot.pages[i];
|
|
3752
|
+
if (!isObj(p)) {
|
|
3753
|
+
setErr('snapshot_page_invalid', `Snapshot pages[${i}] must be an object.`);
|
|
3754
|
+
continue;
|
|
3755
|
+
}
|
|
3756
|
+
if (p.archived === true || p.in_trash === true) continue;
|
|
3757
|
+
const normPageId = normalizeNotionUuid(p.page_id ?? p.id);
|
|
3758
|
+
if (!normPageId) {
|
|
3759
|
+
setErr('snapshot_page_invalid_uuid', `Snapshot pages[${i}] has invalid or missing Notion UUID page_id.`);
|
|
3760
|
+
continue;
|
|
3761
|
+
}
|
|
3762
|
+
if (p.canonical_key !== undefined && p.canonical_key !== null && p.canonical_key !== expectedCanonicalKey) {
|
|
3763
|
+
setErr('snapshot_page_canonical_key_mismatch', `Snapshot pages[${i}] canonical_key does not match expected "${expectedCanonicalKey}".`);
|
|
3764
|
+
continue;
|
|
3765
|
+
}
|
|
3766
|
+
if (p.sync_hash !== undefined && p.sync_hash !== null && (typeof p.sync_hash !== 'string' || !HEX16_RE.test(p.sync_hash))) {
|
|
3767
|
+
setErr('snapshot_page_invalid_sync_hash', `Snapshot pages[${i}].sync_hash must be a 16-char lowercase hex string or null.`);
|
|
3768
|
+
continue;
|
|
3769
|
+
}
|
|
3770
|
+
const nextHash = p.sync_hash ?? null;
|
|
3771
|
+
if (seenPages.has(normPageId)) {
|
|
3772
|
+
if (seenPages.get(normPageId) !== nextHash) {
|
|
3773
|
+
setErr('snapshot_conflicting_page_hash', `Conflicting sync_hash values for duplicate page_id "${normPageId}" in query snapshot.`);
|
|
3774
|
+
}
|
|
3775
|
+
continue;
|
|
3776
|
+
}
|
|
3777
|
+
seenPages.set(normPageId, nextHash);
|
|
3778
|
+
activePages.push({ page_id: normPageId, sync_hash: nextHash });
|
|
3779
|
+
}
|
|
3780
|
+
activePages.sort((a, b) => codePointCompare(a.page_id, b.page_id));
|
|
3781
|
+
}
|
|
3782
|
+
|
|
3783
|
+
return {
|
|
3784
|
+
valid: errors.length === 0,
|
|
3785
|
+
complete: errors.length === 0,
|
|
3786
|
+
code,
|
|
3787
|
+
errors,
|
|
3788
|
+
active_pages: errors.length === 0 ? activePages : [],
|
|
3789
|
+
queried_at: errors.length === 0 ? queriedAt : null,
|
|
3790
|
+
};
|
|
3791
|
+
}
|
|
3792
|
+
|
|
3793
|
+
const RECONCILABLE_STATES = new Set(['in_flight', 'receipt_uncertain', 'conflict_duplicate_remote']);
|
|
3794
|
+
|
|
3795
|
+
// Safe reconciliation of in_flight, receipt_uncertain, or conflict_duplicate_remote records
|
|
3796
|
+
// from a validated complete remote query snapshot (Safety Resolution 2).
|
|
3797
|
+
export function reconcileSyncRecord(root, {
|
|
3798
|
+
database,
|
|
3799
|
+
canonicalKey,
|
|
3800
|
+
expectedDatabaseId,
|
|
3801
|
+
querySnapshot,
|
|
3802
|
+
confirmRemotePageDeleted = false,
|
|
3803
|
+
nowIso = new Date().toISOString(),
|
|
3804
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
3805
|
+
home = os.homedir(),
|
|
3806
|
+
} = {}) {
|
|
3807
|
+
if (!isNonEmptyString(root)) {
|
|
3808
|
+
throw new Error('reconcileSyncRecord requires a non-empty workspace root path.');
|
|
3809
|
+
}
|
|
3810
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
3811
|
+
throw new Error(`reconcileSyncRecord: invalid database "${database}".`);
|
|
3812
|
+
}
|
|
3813
|
+
if (!isNonEmptyString(canonicalKey)) {
|
|
3814
|
+
throw new Error('reconcileSyncRecord requires a non-empty canonicalKey.');
|
|
3815
|
+
}
|
|
3816
|
+
if (normalizeNotionUuid(expectedDatabaseId) === null) {
|
|
3817
|
+
throw new Error('reconcileSyncRecord requires a valid Notion UUID expectedDatabaseId.');
|
|
3818
|
+
}
|
|
3819
|
+
if (typeof confirmRemotePageDeleted !== 'boolean') {
|
|
3820
|
+
throw new Error('reconcileSyncRecord: confirmRemotePageDeleted must be an explicit boolean.');
|
|
3821
|
+
}
|
|
3822
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
3823
|
+
throw new Error(`reconcileSyncRecord: invalid nowIso timestamp "${nowIso}".`);
|
|
3824
|
+
}
|
|
3825
|
+
|
|
3826
|
+
return withSyncStateLock(root, { home, nowIso }, () => {
|
|
3827
|
+
const loaded = loadSyncState(root, { home });
|
|
3828
|
+
if (!loaded.exists) {
|
|
3829
|
+
throw new Error('reconcileSyncRecord: logs/sync-state.json does not exist.');
|
|
3830
|
+
}
|
|
3831
|
+
const integrity = verifySyncStateIntegrity(loaded.state, { nowIso, maxFutureSkewMs });
|
|
3832
|
+
if (!integrity.valid) {
|
|
3833
|
+
throw new Error(`Sync-state integrity check failed: ${integrity.errors.join('; ')}`);
|
|
3834
|
+
}
|
|
3835
|
+
|
|
3836
|
+
const stateKey = makeSyncStateKey(database, canonicalKey);
|
|
3837
|
+
const entry = loaded.state.records[stateKey];
|
|
3838
|
+
if (!entry || !RECONCILABLE_STATES.has(entry.state)) {
|
|
3839
|
+
throw new Error(`reconcileSyncRecord: "${stateKey}" is in state "${entry?.state ?? 'none'}", which is not reconcilable.`);
|
|
3840
|
+
}
|
|
3841
|
+
|
|
3842
|
+
const snapCheck = validateReconcileQuerySnapshot(querySnapshot, {
|
|
3843
|
+
expectedDatabase: database,
|
|
3844
|
+
expectedCanonicalKey: canonicalKey,
|
|
3845
|
+
expectedDatabaseId,
|
|
3846
|
+
minQueriedAt: entry.attempted_at ?? null,
|
|
3847
|
+
nowIso,
|
|
3848
|
+
maxFutureSkewMs,
|
|
3849
|
+
});
|
|
3850
|
+
|
|
3851
|
+
const persistNext = nextEntry => {
|
|
3852
|
+
const nextStateDoc = {
|
|
3853
|
+
schema_version: '1.0',
|
|
3854
|
+
updated_at: nowIso,
|
|
3855
|
+
records: {
|
|
3856
|
+
...loaded.state.records,
|
|
3857
|
+
[stateKey]: nextEntry,
|
|
3858
|
+
},
|
|
3859
|
+
};
|
|
3860
|
+
const nextIntegrity = verifySyncStateIntegrity(nextStateDoc, { nowIso, maxFutureSkewMs });
|
|
3861
|
+
if (!nextIntegrity.valid) {
|
|
3862
|
+
throw new Error(`Refusing to persist invalid post-reconciliation sync state: ${nextIntegrity.errors.join('; ')}`);
|
|
3863
|
+
}
|
|
3864
|
+
return saveSyncState(root, nextStateDoc, { home, nowIso });
|
|
3865
|
+
};
|
|
3866
|
+
|
|
3867
|
+
// Incomplete or invalid snapshot MUST NEVER clear uncertainty or authorize a create
|
|
3868
|
+
if (!snapCheck.valid) {
|
|
3869
|
+
if (entry.state === 'in_flight') {
|
|
3870
|
+
const heldEntry = {
|
|
3871
|
+
...entry,
|
|
3872
|
+
state: 'receipt_uncertain',
|
|
3873
|
+
last_error: sanitizeSafeErrorText(`incomplete_reconcile_query:${snapCheck.code || 'invalid'}`, 'incomplete_reconcile_query'),
|
|
3874
|
+
};
|
|
3875
|
+
const saved = persistNext(heldEntry);
|
|
3876
|
+
return {
|
|
3877
|
+
reconciled: false,
|
|
3878
|
+
state_key: stateKey,
|
|
3879
|
+
previous_state: 'in_flight',
|
|
3880
|
+
state: 'receipt_uncertain',
|
|
3881
|
+
resolution: 'held_incomplete_query',
|
|
3882
|
+
code: snapCheck.code,
|
|
3883
|
+
errors: snapCheck.errors,
|
|
3884
|
+
path: saved.path,
|
|
3885
|
+
sync_state: saved.state,
|
|
3886
|
+
};
|
|
3887
|
+
}
|
|
3888
|
+
return {
|
|
3889
|
+
reconciled: false,
|
|
3890
|
+
state_key: stateKey,
|
|
3891
|
+
previous_state: entry.state,
|
|
3892
|
+
state: entry.state,
|
|
3893
|
+
resolution: 'held_incomplete_query',
|
|
3894
|
+
code: snapCheck.code,
|
|
3895
|
+
errors: snapCheck.errors,
|
|
3896
|
+
path: loaded.path,
|
|
3897
|
+
sync_state: loaded.state,
|
|
3898
|
+
};
|
|
3899
|
+
}
|
|
3900
|
+
|
|
3901
|
+
// Check cross-key page_id collisions across all active pages in the snapshot
|
|
3902
|
+
for (const page of snapCheck.active_pages) {
|
|
3903
|
+
const collisionKey = findCrossKeyPageCollision(loaded.state.records, stateKey, page.page_id);
|
|
3904
|
+
if (collisionKey) {
|
|
3905
|
+
const errMsg = `Reconciled page_id "${page.page_id}" collides with existing key "${collisionKey}".`;
|
|
3906
|
+
if (entry.state === 'in_flight') {
|
|
3907
|
+
const heldEntry = {
|
|
3908
|
+
...entry,
|
|
3909
|
+
state: 'receipt_uncertain',
|
|
3910
|
+
last_error: 'reconcile_page_id_cross_key_collision',
|
|
3911
|
+
};
|
|
3912
|
+
const saved = persistNext(heldEntry);
|
|
3913
|
+
return {
|
|
3914
|
+
reconciled: false,
|
|
3915
|
+
state_key: stateKey,
|
|
3916
|
+
previous_state: 'in_flight',
|
|
3917
|
+
state: 'receipt_uncertain',
|
|
3918
|
+
resolution: 'held_cross_key_page_collision',
|
|
3919
|
+
code: 'reconcile_page_id_cross_key_collision',
|
|
3920
|
+
errors: [errMsg],
|
|
3921
|
+
path: saved.path,
|
|
3922
|
+
sync_state: saved.state,
|
|
3923
|
+
};
|
|
3924
|
+
}
|
|
3925
|
+
return {
|
|
3926
|
+
reconciled: false,
|
|
3927
|
+
state_key: stateKey,
|
|
3928
|
+
previous_state: entry.state,
|
|
3929
|
+
state: entry.state,
|
|
3930
|
+
resolution: 'held_cross_key_page_collision',
|
|
3931
|
+
code: 'reconcile_page_id_cross_key_collision',
|
|
3932
|
+
errors: [errMsg],
|
|
3933
|
+
path: loaded.path,
|
|
3934
|
+
sync_state: loaded.state,
|
|
3935
|
+
};
|
|
3936
|
+
}
|
|
3937
|
+
}
|
|
3938
|
+
|
|
3939
|
+
const activePages = snapCheck.active_pages;
|
|
3940
|
+
let nextEntry;
|
|
3941
|
+
let resolution;
|
|
3942
|
+
let reconciled = true;
|
|
3943
|
+
|
|
3944
|
+
if (activePages.length >= 2) {
|
|
3945
|
+
resolution = 'conflict_duplicate_remote';
|
|
3946
|
+
nextEntry = {
|
|
3947
|
+
database: entry.database,
|
|
3948
|
+
canonical_key: entry.canonical_key,
|
|
3949
|
+
state: 'conflict_duplicate_remote',
|
|
3950
|
+
page_id: null,
|
|
3951
|
+
last_synced_hash: entry.last_synced_hash ?? null,
|
|
3952
|
+
attempted_hash: entry.attempted_hash ?? null,
|
|
3953
|
+
attempted_at: entry.attempted_at ?? null,
|
|
3954
|
+
last_synced_at: entry.last_synced_at ?? null,
|
|
3955
|
+
operation_id: entry.operation_id ?? null,
|
|
3956
|
+
approved_plan_hash: entry.approved_plan_hash ?? null,
|
|
3957
|
+
retry_count: Number.isInteger(entry.retry_count) ? entry.retry_count : 0,
|
|
3958
|
+
next_retry_after: null,
|
|
3959
|
+
conflicting_page_ids: activePages.map(p => p.page_id),
|
|
3960
|
+
last_error: 'duplicate_remote_pages',
|
|
3961
|
+
};
|
|
3962
|
+
} else if (activePages.length === 1) {
|
|
3963
|
+
const remote = activePages[0];
|
|
3964
|
+
const expectedHash = entry.attempted_hash ?? entry.last_synced_hash ?? null;
|
|
3965
|
+
if (expectedHash !== null && remote.sync_hash === expectedHash) {
|
|
3966
|
+
resolution = 'verified_synced';
|
|
3967
|
+
nextEntry = {
|
|
3968
|
+
database: entry.database,
|
|
3969
|
+
canonical_key: entry.canonical_key,
|
|
3970
|
+
state: 'synced',
|
|
3971
|
+
page_id: remote.page_id,
|
|
3972
|
+
last_synced_hash: expectedHash,
|
|
3973
|
+
attempted_hash: null,
|
|
3974
|
+
attempted_at: null,
|
|
3975
|
+
last_synced_at: snapCheck.queried_at,
|
|
3976
|
+
operation_id: null,
|
|
3977
|
+
approved_plan_hash: null,
|
|
3978
|
+
retry_count: 0,
|
|
3979
|
+
next_retry_after: null,
|
|
3980
|
+
last_error: null,
|
|
3981
|
+
};
|
|
3982
|
+
} else {
|
|
3983
|
+
// Remote page exists but has older/missing/different hash -> bind page_id so next plan emits safe update (never create!)
|
|
3984
|
+
resolution = 'rebound_pending_update';
|
|
3985
|
+
nextEntry = {
|
|
3986
|
+
database: entry.database,
|
|
3987
|
+
canonical_key: entry.canonical_key,
|
|
3988
|
+
state: 'pending_sync',
|
|
3989
|
+
page_id: remote.page_id,
|
|
3990
|
+
last_synced_hash: remote.sync_hash ?? entry.last_synced_hash ?? null,
|
|
3991
|
+
attempted_hash: null,
|
|
3992
|
+
attempted_at: null,
|
|
3993
|
+
last_synced_at: entry.last_synced_at ?? null,
|
|
3994
|
+
operation_id: null,
|
|
3995
|
+
approved_plan_hash: null,
|
|
3996
|
+
retry_count: 0,
|
|
3997
|
+
next_retry_after: null,
|
|
3998
|
+
last_error: null,
|
|
3999
|
+
};
|
|
4000
|
+
}
|
|
4001
|
+
} else {
|
|
4002
|
+
// activePages.length === 0 with all 6 completeness checks passed
|
|
4003
|
+
const hadKnownPageId = entry.page_id !== undefined && entry.page_id !== null;
|
|
4004
|
+
if (hadKnownPageId && !confirmRemotePageDeleted) {
|
|
4005
|
+
reconciled = false;
|
|
4006
|
+
resolution = 'held_deleted_page_confirmation_required';
|
|
4007
|
+
nextEntry = {
|
|
4008
|
+
...entry,
|
|
4009
|
+
state: 'receipt_uncertain',
|
|
4010
|
+
last_error: 'remote_page_deleted_requires_confirmation',
|
|
4011
|
+
};
|
|
4012
|
+
} else {
|
|
4013
|
+
resolution = hadKnownPageId ? 'confirmed_remote_deleted_pending_create' : 'confirmed_absent_pending_create';
|
|
4014
|
+
nextEntry = {
|
|
4015
|
+
database: entry.database,
|
|
4016
|
+
canonical_key: entry.canonical_key,
|
|
4017
|
+
state: 'pending_sync',
|
|
4018
|
+
page_id: null,
|
|
4019
|
+
last_synced_hash: null,
|
|
4020
|
+
attempted_hash: null,
|
|
4021
|
+
attempted_at: null,
|
|
4022
|
+
last_synced_at: entry.last_synced_at ?? null,
|
|
4023
|
+
operation_id: null,
|
|
4024
|
+
approved_plan_hash: null,
|
|
4025
|
+
retry_count: 0,
|
|
4026
|
+
next_retry_after: null,
|
|
4027
|
+
last_error: null,
|
|
4028
|
+
};
|
|
4029
|
+
}
|
|
4030
|
+
}
|
|
4031
|
+
|
|
4032
|
+
const saved = persistNext(nextEntry);
|
|
4033
|
+
return {
|
|
4034
|
+
reconciled,
|
|
4035
|
+
state_key: stateKey,
|
|
4036
|
+
previous_state: entry.state,
|
|
4037
|
+
state: nextEntry.state,
|
|
4038
|
+
resolution,
|
|
4039
|
+
page_id: nextEntry.page_id ?? null,
|
|
4040
|
+
conflicting_page_ids: nextEntry.conflicting_page_ids ?? [],
|
|
4041
|
+
code: reconciled ? null : (nextEntry.last_error ?? null),
|
|
4042
|
+
errors: [],
|
|
4043
|
+
path: saved.path,
|
|
4044
|
+
sync_state: saved.state,
|
|
4045
|
+
};
|
|
4046
|
+
});
|
|
4047
|
+
}
|
|
4048
|
+
|
|
4049
|
+
// D4: Separate explicit owner-confirmed reset for failed_permanent -> pending_sync.
|
|
4050
|
+
// Never triggered automatically, never triggered by payload changes, never triggered by --force.
|
|
4051
|
+
export function resetPermanentFailure(root, {
|
|
4052
|
+
database,
|
|
4053
|
+
canonicalKey,
|
|
4054
|
+
expectedLastError,
|
|
4055
|
+
resetReason,
|
|
4056
|
+
confirmedByOwner = false,
|
|
4057
|
+
nowIso = new Date().toISOString(),
|
|
4058
|
+
maxFutureSkewMs = DEFAULT_MAX_FUTURE_SKEW_MS,
|
|
4059
|
+
home = os.homedir(),
|
|
4060
|
+
} = {}) {
|
|
4061
|
+
if (confirmedByOwner !== true) {
|
|
4062
|
+
throw new Error('resetPermanentFailure requires explicit confirmedByOwner === true.');
|
|
4063
|
+
}
|
|
4064
|
+
if (!isNonEmptyString(root)) {
|
|
4065
|
+
throw new Error('resetPermanentFailure requires a non-empty workspace root path.');
|
|
4066
|
+
}
|
|
4067
|
+
if (!TARGET_DATABASE_SET.has(database)) {
|
|
4068
|
+
throw new Error(`resetPermanentFailure: invalid database "${database}".`);
|
|
4069
|
+
}
|
|
4070
|
+
if (!isNonEmptyString(canonicalKey)) {
|
|
4071
|
+
throw new Error('resetPermanentFailure requires a non-empty canonicalKey.');
|
|
4072
|
+
}
|
|
4073
|
+
if (expectedLastError === undefined) {
|
|
4074
|
+
throw new Error('resetPermanentFailure requires explicit expectedLastError (string or null) matching the reviewed error.');
|
|
4075
|
+
}
|
|
4076
|
+
if (!isNonEmptyString(resetReason) || hasDisallowedLastErrorContent(resetReason)) {
|
|
4077
|
+
throw new Error('resetPermanentFailure requires a non-empty safe resetReason without secrets, emails, or local paths.');
|
|
4078
|
+
}
|
|
4079
|
+
if (!isValidIsoDateTime(nowIso)) {
|
|
4080
|
+
throw new Error(`resetPermanentFailure: invalid nowIso timestamp "${nowIso}".`);
|
|
4081
|
+
}
|
|
4082
|
+
|
|
4083
|
+
return withSyncStateLock(root, { home, nowIso }, () => {
|
|
4084
|
+
const loaded = loadSyncState(root, { home });
|
|
4085
|
+
if (!loaded.exists) {
|
|
4086
|
+
throw new Error('resetPermanentFailure: logs/sync-state.json does not exist.');
|
|
4087
|
+
}
|
|
4088
|
+
const integrity = verifySyncStateIntegrity(loaded.state, { nowIso, maxFutureSkewMs });
|
|
4089
|
+
if (!integrity.valid) {
|
|
4090
|
+
throw new Error(`Sync-state integrity check failed: ${integrity.errors.join('; ')}`);
|
|
4091
|
+
}
|
|
4092
|
+
|
|
4093
|
+
const stateKey = makeSyncStateKey(database, canonicalKey);
|
|
4094
|
+
const entry = loaded.state.records[stateKey];
|
|
4095
|
+
if (!entry || entry.state !== 'failed_permanent') {
|
|
4096
|
+
throw new Error(`resetPermanentFailure: "${stateKey}" is not in failed_permanent (current state: "${entry?.state ?? 'none'}").`);
|
|
4097
|
+
}
|
|
4098
|
+
const currentError = entry.last_error ?? null;
|
|
4099
|
+
if (currentError !== expectedLastError) {
|
|
4100
|
+
throw new Error(`resetPermanentFailure: expectedLastError "${expectedLastError}" does not match current last_error "${currentError}".`);
|
|
4101
|
+
}
|
|
4102
|
+
|
|
4103
|
+
const nextEntry = {
|
|
4104
|
+
database: entry.database,
|
|
4105
|
+
canonical_key: entry.canonical_key,
|
|
4106
|
+
state: 'pending_sync',
|
|
4107
|
+
page_id: entry.page_id ?? null,
|
|
4108
|
+
last_synced_hash: entry.last_synced_hash ?? null,
|
|
4109
|
+
attempted_hash: null,
|
|
4110
|
+
attempted_at: null,
|
|
4111
|
+
last_synced_at: entry.last_synced_at ?? null,
|
|
4112
|
+
operation_id: null,
|
|
4113
|
+
approved_plan_hash: null,
|
|
4114
|
+
retry_count: 0,
|
|
4115
|
+
next_retry_after: null,
|
|
4116
|
+
last_error: null,
|
|
4117
|
+
};
|
|
4118
|
+
|
|
4119
|
+
const nextStateDoc = {
|
|
4120
|
+
schema_version: '1.0',
|
|
4121
|
+
updated_at: nowIso,
|
|
4122
|
+
records: {
|
|
4123
|
+
...loaded.state.records,
|
|
4124
|
+
[stateKey]: nextEntry,
|
|
4125
|
+
},
|
|
4126
|
+
};
|
|
4127
|
+
const nextIntegrity = verifySyncStateIntegrity(nextStateDoc, { nowIso, maxFutureSkewMs });
|
|
4128
|
+
if (!nextIntegrity.valid) {
|
|
4129
|
+
throw new Error(`Refusing to persist invalid post-reset sync state: ${nextIntegrity.errors.join('; ')}`);
|
|
4130
|
+
}
|
|
4131
|
+
|
|
4132
|
+
const saved = saveSyncState(root, nextStateDoc, { home, nowIso });
|
|
4133
|
+
return {
|
|
4134
|
+
reset: true,
|
|
4135
|
+
state_key: stateKey,
|
|
4136
|
+
previous_state: 'failed_permanent',
|
|
4137
|
+
previous_error: currentError,
|
|
4138
|
+
state: 'pending_sync',
|
|
4139
|
+
page_id: nextEntry.page_id,
|
|
4140
|
+
reset_reason: resetReason.trim(),
|
|
4141
|
+
path: saved.path,
|
|
4142
|
+
sync_state: saved.state,
|
|
4143
|
+
};
|
|
4144
|
+
});
|
|
4145
|
+
}
|
|
4146
|
+
|
|
4147
|
+
// ---------------- Stage 3 (T9): Thin CLI Command Adapter for `veycraft career sync` ----------------
|
|
4148
|
+
|
|
4149
|
+
function readGuardrailsSyncSettings(root, sourceRoot = null, { home = os.homedir() } = {}) {
|
|
4150
|
+
const workspaceConfig = path.join(root, 'config', 'guardrails.yaml');
|
|
4151
|
+
const fallbackConfig = sourceRoot ? path.join(sourceRoot, 'config', 'guardrails.yaml') : null;
|
|
4152
|
+
const workspaceExists = fs.existsSync(workspaceConfig);
|
|
4153
|
+
const found = workspaceExists
|
|
4154
|
+
? workspaceConfig
|
|
4155
|
+
: (fallbackConfig && fs.existsSync(fallbackConfig) ? fallbackConfig : null);
|
|
4156
|
+
|
|
4157
|
+
let dryRun = true;
|
|
4158
|
+
let notionMcpEnabled = false;
|
|
4159
|
+
let explicitDryRun = false;
|
|
4160
|
+
let explicitNotionMcp = false;
|
|
4161
|
+
let parseError = null;
|
|
4162
|
+
|
|
4163
|
+
if (!found) {
|
|
4164
|
+
parseError = 'config/guardrails.yaml not found';
|
|
4165
|
+
} else {
|
|
4166
|
+
try {
|
|
4167
|
+
if (workspaceExists) {
|
|
4168
|
+
refuseSymlink(workspaceConfig, root, home);
|
|
4169
|
+
}
|
|
4170
|
+
const text = fs.readFileSync(found, 'utf8');
|
|
4171
|
+
if (!isNonEmptyString(text)) {
|
|
4172
|
+
parseError = 'config/guardrails.yaml is empty';
|
|
4173
|
+
} else {
|
|
4174
|
+
const dryMatches = [...text.matchAll(/^[ \t]*dry_run:[ \t]*([^\s#]+)[ \t]*(?:#.*)?$/gm)];
|
|
4175
|
+
if (dryMatches.length === 1 && (dryMatches[0][1] === 'true' || dryMatches[0][1] === 'false')) {
|
|
4176
|
+
explicitDryRun = true;
|
|
4177
|
+
dryRun = dryMatches[0][1] === 'true';
|
|
4178
|
+
} else if (dryMatches.length > 0) {
|
|
4179
|
+
parseError = 'malformed or duplicate dry_run setting in config/guardrails.yaml';
|
|
4180
|
+
}
|
|
4181
|
+
|
|
4182
|
+
const adapterBlock = text.match(/^[ \t]*storage_adapters:[ \t]*(?:#.*)?\r?\n((?:[ \t]+.*\r?\n?)*)/m);
|
|
4183
|
+
if (adapterBlock) {
|
|
4184
|
+
const nmMatches = [...adapterBlock[1].matchAll(/^[ \t]+notion_mcp:[ \t]*([^\s#]+)[ \t]*(?:#.*)?$/gm)];
|
|
4185
|
+
if (nmMatches.length === 1 && (nmMatches[0][1] === 'true' || nmMatches[0][1] === 'false')) {
|
|
4186
|
+
explicitNotionMcp = true;
|
|
4187
|
+
notionMcpEnabled = nmMatches[0][1] === 'true';
|
|
4188
|
+
} else if (nmMatches.length > 0) {
|
|
4189
|
+
parseError = parseError || 'malformed or duplicate storage_adapters.notion_mcp setting in config/guardrails.yaml';
|
|
4190
|
+
}
|
|
4191
|
+
}
|
|
4192
|
+
}
|
|
4193
|
+
} catch (err) {
|
|
4194
|
+
parseError = err instanceof Error ? err.message : String(err);
|
|
4195
|
+
}
|
|
4196
|
+
}
|
|
4197
|
+
|
|
4198
|
+
return {
|
|
4199
|
+
config_path: found,
|
|
4200
|
+
workspace_config_present: workspaceExists,
|
|
4201
|
+
dry_run: dryRun,
|
|
4202
|
+
notion_mcp_enabled: notionMcpEnabled,
|
|
4203
|
+
explicit_dry_run: explicitDryRun,
|
|
4204
|
+
explicit_notion_mcp: explicitNotionMcp,
|
|
4205
|
+
parse_error: parseError,
|
|
4206
|
+
};
|
|
4207
|
+
}
|
|
4208
|
+
|
|
4209
|
+
function assertLiveSyncGuardrails(guardrails, subcommandLabel) {
|
|
4210
|
+
if (!guardrails || guardrails.parse_error) {
|
|
4211
|
+
throw new Error(`Refusing \`career sync ${subcommandLabel}\`: invalid or unreadable config/guardrails.yaml (${guardrails?.parse_error || 'missing'}).`);
|
|
4212
|
+
}
|
|
4213
|
+
if (!guardrails.explicit_notion_mcp || guardrails.notion_mcp_enabled !== true) {
|
|
4214
|
+
throw new Error(`Refusing \`career sync ${subcommandLabel}\`: config/guardrails.yaml has storage_adapters.notion_mcp: false (or unset).`);
|
|
4215
|
+
}
|
|
4216
|
+
if (!guardrails.explicit_dry_run || guardrails.dry_run !== false) {
|
|
4217
|
+
throw new Error(`Refusing \`career sync ${subcommandLabel}\`: config/guardrails.yaml has dry_run: true (or unset).`);
|
|
4218
|
+
}
|
|
4219
|
+
}
|
|
4220
|
+
|
|
4221
|
+
function readSyncCliJsonFile(rawPath, { root, home }) {
|
|
4222
|
+
if (!isNonEmptyString(rawPath)) {
|
|
4223
|
+
throw new Error('JSON file path must be a non-empty string.');
|
|
4224
|
+
}
|
|
4225
|
+
const resolved = path.resolve(process.cwd(), rawPath);
|
|
4226
|
+
if (isWithinDir(resolved, root) || isWithinDir(resolved, home)) {
|
|
4227
|
+
refuseSymlink(resolved, root, home);
|
|
4228
|
+
}
|
|
4229
|
+
if (!fs.existsSync(resolved)) {
|
|
4230
|
+
throw new Error(`Input JSON file not found: ${resolved}`);
|
|
4231
|
+
}
|
|
4232
|
+
try {
|
|
4233
|
+
return JSON.parse(fs.readFileSync(resolved, 'utf8'));
|
|
4234
|
+
} catch (err) {
|
|
4235
|
+
throw new Error(`Invalid JSON in ${resolved}: ${err.message}`);
|
|
4236
|
+
}
|
|
4237
|
+
}
|
|
4238
|
+
|
|
4239
|
+
function writeSyncCliJsonOut(rawOutPath, payload, { root, home }) {
|
|
4240
|
+
const resolved = path.resolve(root, rawOutPath);
|
|
4241
|
+
if (!isWithinDir(resolved, root)) {
|
|
4242
|
+
throw new Error(`Refusing --out path outside workspace root "${root}": ${resolved}`);
|
|
4243
|
+
}
|
|
4244
|
+
refuseSymlink(resolved, root, home);
|
|
4245
|
+
writeAtomic(resolved, JSON.stringify(payload, null, 2) + '\n', {
|
|
4246
|
+
mode: 0o600,
|
|
4247
|
+
boundary: root,
|
|
4248
|
+
home,
|
|
4249
|
+
});
|
|
4250
|
+
return resolved;
|
|
4251
|
+
}
|
|
4252
|
+
|
|
4253
|
+
function parseScopedSyncFlags(rawArgs, { booleans = [], values = [] } = {}) {
|
|
4254
|
+
const boolSet = new Set(['--json', '--help', '-h', ...booleans]);
|
|
4255
|
+
const valSet = new Set(values);
|
|
4256
|
+
const parsed = { json: false, help: false };
|
|
4257
|
+
const extras = [];
|
|
4258
|
+
|
|
4259
|
+
const toCamel = flag => flag.replace(/^--/, '').replace(/-([a-z])/g, (_, c) => c.toUpperCase());
|
|
4260
|
+
|
|
4261
|
+
for (let i = 0; i < rawArgs.length; i++) {
|
|
4262
|
+
const tok = rawArgs[i];
|
|
4263
|
+
if (tok === '--help' || tok === '-h') {
|
|
4264
|
+
parsed.help = true;
|
|
4265
|
+
continue;
|
|
4266
|
+
}
|
|
4267
|
+
if (tok === '--json') {
|
|
4268
|
+
parsed.json = true;
|
|
4269
|
+
continue;
|
|
4270
|
+
}
|
|
4271
|
+
if (boolSet.has(tok)) {
|
|
4272
|
+
parsed[toCamel(tok)] = true;
|
|
4273
|
+
continue;
|
|
4274
|
+
}
|
|
4275
|
+
const eqIdx = tok.indexOf('=');
|
|
4276
|
+
const flagName = eqIdx !== -1 ? tok.slice(0, eqIdx) : tok;
|
|
4277
|
+
if (valSet.has(flagName)) {
|
|
4278
|
+
let val;
|
|
4279
|
+
if (eqIdx !== -1) {
|
|
4280
|
+
val = tok.slice(eqIdx + 1);
|
|
4281
|
+
} else {
|
|
4282
|
+
val = rawArgs[++i];
|
|
4283
|
+
}
|
|
4284
|
+
if (val === undefined || val === '') {
|
|
4285
|
+
throw new Error(`Option ${flagName} requires a value.`);
|
|
4286
|
+
}
|
|
4287
|
+
parsed[toCamel(flagName)] = val;
|
|
4288
|
+
continue;
|
|
4289
|
+
}
|
|
4290
|
+
if (tok.startsWith('-')) {
|
|
4291
|
+
throw new Error(`Unsupported option "${tok}" for this \`veycraft career sync\` subcommand.`);
|
|
4292
|
+
}
|
|
4293
|
+
extras.push(tok);
|
|
4294
|
+
}
|
|
4295
|
+
if (extras.length > 0) {
|
|
4296
|
+
throw new Error(`Unexpected positional argument(s): ${extras.join(', ')}`);
|
|
4297
|
+
}
|
|
4298
|
+
return parsed;
|
|
4299
|
+
}
|
|
4300
|
+
|
|
4301
|
+
export const CAREER_SYNC_SUBCOMMANDS = Object.freeze([
|
|
4302
|
+
'preview',
|
|
4303
|
+
'status',
|
|
4304
|
+
'verify-schema',
|
|
4305
|
+
'approve',
|
|
4306
|
+
'mark-in-flight',
|
|
4307
|
+
'apply-receipt',
|
|
4308
|
+
'record-failure',
|
|
4309
|
+
'expire-stale',
|
|
4310
|
+
'reconcile',
|
|
4311
|
+
'reset-permanent',
|
|
4312
|
+
'release-stale-lock',
|
|
4313
|
+
]);
|
|
4314
|
+
|
|
4315
|
+
function formatCareerSyncHelp() {
|
|
4316
|
+
return [
|
|
4317
|
+
'Usage: veycraft career sync <subcommand> [options]',
|
|
4318
|
+
'',
|
|
4319
|
+
'Offline / Read-Only Subcommands (work even when storage_adapters.notion_mcp is false):',
|
|
4320
|
+
' preview [--file <remote-index.json>] [--out <plan.json>] [--live] [--json]',
|
|
4321
|
+
' status [--json]',
|
|
4322
|
+
' verify-schema --database <applications|daily_runs|insights> --file <schema.json> [--json]',
|
|
4323
|
+
'',
|
|
4324
|
+
'Approval, Pre-Write Reservation & Lifecycle Subcommands (local state only; zero external writes):',
|
|
4325
|
+
' approve --file <plan.json> --plan-hash <64hex> --confirm-approve [--out <approved.json>] [--json]',
|
|
4326
|
+
' mark-in-flight --file <approved.json> --op <operation_id> [--force] [--json]',
|
|
4327
|
+
' apply-receipt --database <db> --key <key> --op <op_id> --plan-hash <64hex> --file <receipt.json> [--database-id <uuid>] [--json]',
|
|
4328
|
+
' record-failure --database <db> --key <key> --op <op_id> --plan-hash <64hex> --error-code <code> [--error-message <msg>] [--mutation-not-applied] [--json]',
|
|
4329
|
+
' expire-stale [--timeout-minutes <n>] [--json]',
|
|
4330
|
+
' reconcile --database <db> --key <key> --database-id <uuid> --file <snapshot.json> [--confirm-remote-deleted] [--json]',
|
|
4331
|
+
' reset-permanent --database <db> --key <key> --expected-error <err|null> --reason <text> --confirm-reset [--json]',
|
|
4332
|
+
' release-stale-lock --nonce <nonce> --confirm-unlock [--json]',
|
|
4333
|
+
];
|
|
4334
|
+
}
|
|
4335
|
+
|
|
4336
|
+
// Thin, transport-free CLI adapter dispatching `veycraft career sync <subcommand>` to T7/T8-A/T8-B/T8-C APIs.
|
|
4337
|
+
export function runNotionSyncCli(root, argv = [], {
|
|
4338
|
+
home = os.homedir(),
|
|
4339
|
+
sourceRoot = null,
|
|
4340
|
+
loadInputs = null,
|
|
4341
|
+
nowIso = new Date().toISOString(),
|
|
4342
|
+
} = {}) {
|
|
4343
|
+
const first = (argv[0] || '').toLowerCase();
|
|
4344
|
+
if (!first || first === 'help' || first === '--help' || first === '-h') {
|
|
4345
|
+
return {
|
|
4346
|
+
json: false,
|
|
4347
|
+
exitCode: 0,
|
|
4348
|
+
data: { subcommands: CAREER_SYNC_SUBCOMMANDS },
|
|
4349
|
+
lines: formatCareerSyncHelp(),
|
|
4350
|
+
};
|
|
4351
|
+
}
|
|
4352
|
+
|
|
4353
|
+
const sub = first;
|
|
4354
|
+
const rest = argv.slice(1);
|
|
4355
|
+
const guardrails = readGuardrailsSyncSettings(root, sourceRoot, { home });
|
|
4356
|
+
|
|
4357
|
+
if (sub === 'status') {
|
|
4358
|
+
const flags = parseScopedSyncFlags(rest);
|
|
4359
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4360
|
+
const loaded = loadSyncState(root, { home });
|
|
4361
|
+
const recovery = inspectSyncStateRecovery(loaded.state, { nowIso });
|
|
4362
|
+
const lock = inspectSyncStateLock(root, { home, nowIso });
|
|
4363
|
+
const data = {
|
|
4364
|
+
root,
|
|
4365
|
+
sync_state_exists: loaded.exists,
|
|
4366
|
+
sync_state_path: loaded.path,
|
|
4367
|
+
guardrails: {
|
|
4368
|
+
dry_run: guardrails.dry_run,
|
|
4369
|
+
notion_mcp_enabled: guardrails.notion_mcp_enabled,
|
|
4370
|
+
parse_error: guardrails.parse_error ?? null,
|
|
4371
|
+
},
|
|
4372
|
+
lock,
|
|
4373
|
+
recovery,
|
|
4374
|
+
};
|
|
4375
|
+
const c = recovery.counts;
|
|
4376
|
+
const lines = [
|
|
4377
|
+
`Sync State File: ${loaded.exists ? loaded.path : 'not created yet (clean local state)'}`,
|
|
4378
|
+
`Guardrails: dry_run=${guardrails.dry_run ? 'ON' : 'OFF'} | storage_adapters.notion_mcp=${guardrails.notion_mcp_enabled ? 'ENABLED' : 'DISABLED (offline preview/status available)'}`,
|
|
4379
|
+
...(guardrails.parse_error ? [`Guardrails Warning: ${guardrails.parse_error}`] : []),
|
|
4380
|
+
`Lock Status: ${lock.locked ? `LOCKED (pid=${lock.lock?.pid ?? 'corrupt'}, stale=${lock.stale}, owner_alive=${lock.owner_alive})` : 'unlocked'}`,
|
|
4381
|
+
`Records (${recovery.total_records}): Healthy/Pending: ${c.healthy_or_pending} | Active In-Flight: ${c.active_in_flight} | Stale In-Flight: ${c.stale_in_flight} | Uncertain: ${c.receipt_uncertain} | Conflicts: ${c.conflict_duplicate_remote} | Retryable: ${c.failed_retryable_ready + c.failed_retryable_cooldown + c.failed_retryable_cap_reached} | Permanent: ${c.failed_permanent}`,
|
|
4382
|
+
];
|
|
4383
|
+
return { json: flags.json, exitCode: 0, data, lines };
|
|
4384
|
+
}
|
|
4385
|
+
|
|
4386
|
+
if (sub === 'verify-schema') {
|
|
4387
|
+
const flags = parseScopedSyncFlags(rest, { values: ['--database', '--file'] });
|
|
4388
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4389
|
+
if (!flags.database || !flags.file) {
|
|
4390
|
+
throw new Error('Usage: veycraft career sync verify-schema --database <applications|daily_runs|insights> --file <schema.json> [--json]');
|
|
4391
|
+
}
|
|
4392
|
+
const retrieved = readSyncCliJsonFile(flags.file, { root, home });
|
|
4393
|
+
const res = validateNotionDatabaseSchema(flags.database, retrieved);
|
|
4394
|
+
const lines = res.valid
|
|
4395
|
+
? [`Schema "${flags.database}" verified (${Object.keys(NOTION_DATABASE_SCHEMAS[flags.database]).length} required properties matched, ${res.extra_properties.length} extra column(s) preserved).`]
|
|
4396
|
+
: [`Schema "${flags.database}" FAILED validation:`, ...res.errors.map(e => ` - ${e}`)];
|
|
4397
|
+
return { json: flags.json, exitCode: res.valid ? 0 : 1, data: res, lines };
|
|
4398
|
+
}
|
|
4399
|
+
|
|
4400
|
+
if (sub === 'preview') {
|
|
4401
|
+
const flags = parseScopedSyncFlags(rest, { booleans: ['--live'], values: ['--file', '--out', '--plan-id'] });
|
|
4402
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4403
|
+
if (typeof loadInputs !== 'function') {
|
|
4404
|
+
throw new Error('career sync preview requires a workspace input loader.');
|
|
4405
|
+
}
|
|
4406
|
+
const wantLive = Boolean(flags.live);
|
|
4407
|
+
if (wantLive) {
|
|
4408
|
+
assertLiveSyncGuardrails(guardrails, 'preview --live');
|
|
4409
|
+
}
|
|
4410
|
+
const inputs = loadInputs(root, { home });
|
|
4411
|
+
const loadedState = loadSyncState(root, { home });
|
|
4412
|
+
const remoteIndex = flags.file ? readSyncCliJsonFile(flags.file, { root, home }) : null;
|
|
4413
|
+
const diff = computeNotionSyncDiff({
|
|
4414
|
+
applications: inputs.applications,
|
|
4415
|
+
dailyRuns: inputs.dailyRuns,
|
|
4416
|
+
insights: inputs.insights,
|
|
4417
|
+
allCvRegistry: inputs.cvRegistry,
|
|
4418
|
+
syncState: loadedState.exists ? loadedState.state : null,
|
|
4419
|
+
remoteIndex,
|
|
4420
|
+
planId: flags.planId || null,
|
|
4421
|
+
createdAt: nowIso,
|
|
4422
|
+
transportEnabled: wantLive,
|
|
4423
|
+
dryRun: !wantLive,
|
|
4424
|
+
});
|
|
4425
|
+
let writtenPath = null;
|
|
4426
|
+
if (flags.out) {
|
|
4427
|
+
writtenPath = writeSyncCliJsonOut(flags.out, diff.plan, { root, home });
|
|
4428
|
+
}
|
|
4429
|
+
const s = diff.summary;
|
|
4430
|
+
const data = {
|
|
4431
|
+
...diff,
|
|
4432
|
+
guardrails: {
|
|
4433
|
+
dry_run: guardrails.dry_run,
|
|
4434
|
+
notion_mcp_enabled: guardrails.notion_mcp_enabled,
|
|
4435
|
+
},
|
|
4436
|
+
written_path: writtenPath,
|
|
4437
|
+
};
|
|
4438
|
+
const lines = [
|
|
4439
|
+
`Plan ID: ${diff.plan.plan_id} (${wantLive ? 'live-eligible preview' : 'offline dry-run preview'})`,
|
|
4440
|
+
`Plan Hash: ${diff.plan.plan_hash}`,
|
|
4441
|
+
`Operations: Create: ${s.create} | Update: ${s.update} | Skip Unchanged: ${s.skip_unchanged}`,
|
|
4442
|
+
`Safeguards: Blocked Privacy: ${s.blocked_privacy} | Skipped Ineligible: ${s.skipped_ineligible} | Held: ${s.held}`,
|
|
4443
|
+
...(writtenPath ? [`Saved Preview Plan: ${writtenPath}`] : []),
|
|
4444
|
+
];
|
|
4445
|
+
return { json: flags.json, exitCode: 0, data, lines };
|
|
4446
|
+
}
|
|
4447
|
+
|
|
4448
|
+
if (sub === 'approve') {
|
|
4449
|
+
const flags = parseScopedSyncFlags(rest, { booleans: ['--confirm-approve'], values: ['--file', '--plan-hash', '--out'] });
|
|
4450
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4451
|
+
if (!flags.file || !flags.planHash) {
|
|
4452
|
+
throw new Error('Usage: veycraft career sync approve --file <plan.json> --plan-hash <64hex> --confirm-approve [--out <approved.json>] [--json]');
|
|
4453
|
+
}
|
|
4454
|
+
assertLiveSyncGuardrails(guardrails, 'approve');
|
|
4455
|
+
const previewPlan = readSyncCliJsonFile(flags.file, { root, home });
|
|
4456
|
+
const approvedPlan = approveNotionSyncPlan(previewPlan, {
|
|
4457
|
+
expectedPlanHash: flags.planHash,
|
|
4458
|
+
confirmedByOwner: Boolean(flags.confirmApprove),
|
|
4459
|
+
approvedAt: nowIso,
|
|
4460
|
+
});
|
|
4461
|
+
let writtenPath = null;
|
|
4462
|
+
if (flags.out) {
|
|
4463
|
+
writtenPath = writeSyncCliJsonOut(flags.out, approvedPlan, { root, home });
|
|
4464
|
+
}
|
|
4465
|
+
const data = { approved: true, plan: approvedPlan, written_path: writtenPath };
|
|
4466
|
+
const lines = [
|
|
4467
|
+
`Approved Plan: ${approvedPlan.plan_id} (${approvedPlan.operations.length} operation(s))`,
|
|
4468
|
+
`Approved Plan Hash: ${approvedPlan.plan_hash}`,
|
|
4469
|
+
...(writtenPath ? [`Saved Approved Plan: ${writtenPath}`] : []),
|
|
4470
|
+
];
|
|
4471
|
+
return { json: flags.json, exitCode: 0, data, lines };
|
|
4472
|
+
}
|
|
4473
|
+
|
|
4474
|
+
if (sub === 'mark-in-flight') {
|
|
4475
|
+
const flags = parseScopedSyncFlags(rest, { booleans: ['--force'], values: ['--file', '--op'] });
|
|
4476
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4477
|
+
if (!flags.file || !flags.op) {
|
|
4478
|
+
throw new Error('Usage: veycraft career sync mark-in-flight --file <approved-plan.json> --op <operation_id> [--force] [--json]');
|
|
4479
|
+
}
|
|
4480
|
+
assertLiveSyncGuardrails(guardrails, 'mark-in-flight');
|
|
4481
|
+
const approvedPlan = readSyncCliJsonFile(flags.file, { root, home });
|
|
4482
|
+
const res = reserveOperationInFlight(root, {
|
|
4483
|
+
approvedPlan,
|
|
4484
|
+
operationId: flags.op,
|
|
4485
|
+
nowIso,
|
|
4486
|
+
force: Boolean(flags.force),
|
|
4487
|
+
home,
|
|
4488
|
+
});
|
|
4489
|
+
const lines = [
|
|
4490
|
+
`Reserved In-Flight: ${res.state_key} (${res.action}, op=${res.operation_id})`,
|
|
4491
|
+
`Sync State Path: ${res.path}`,
|
|
4492
|
+
];
|
|
4493
|
+
return { json: flags.json, exitCode: 0, data: res, lines };
|
|
4494
|
+
}
|
|
4495
|
+
|
|
4496
|
+
if (sub === 'apply-receipt') {
|
|
4497
|
+
const flags = parseScopedSyncFlags(rest, { values: ['--database', '--key', '--op', '--plan-hash', '--file', '--database-id'] });
|
|
4498
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4499
|
+
if (!flags.database || !flags.key || !flags.op || !flags.planHash || !flags.file) {
|
|
4500
|
+
throw new Error('Usage: veycraft career sync apply-receipt --database <db> --key <key> --op <op_id> --plan-hash <64hex> --file <receipt.json> [--database-id <uuid>] [--json]');
|
|
4501
|
+
}
|
|
4502
|
+
const receipt = readSyncCliJsonFile(flags.file, { root, home });
|
|
4503
|
+
const res = applySyncReceipt(root, {
|
|
4504
|
+
database: flags.database,
|
|
4505
|
+
canonicalKey: flags.key,
|
|
4506
|
+
operationId: flags.op,
|
|
4507
|
+
approvedPlanHash: flags.planHash,
|
|
4508
|
+
receipt,
|
|
4509
|
+
expectedDatabaseId: flags.databaseId || null,
|
|
4510
|
+
nowIso,
|
|
4511
|
+
home,
|
|
4512
|
+
});
|
|
4513
|
+
const lines = res.applied
|
|
4514
|
+
? [`Receipt Verified: ${res.state_key} -> synced (page_id=${res.page_id})`, `Trust Note: ${res.trust_note}`]
|
|
4515
|
+
: [`Receipt Held: ${res.state_key} -> ${res.state} (${res.code || 'verification_failed'})`];
|
|
4516
|
+
return { json: flags.json, exitCode: res.applied ? 0 : 1, data: res, lines };
|
|
4517
|
+
}
|
|
4518
|
+
|
|
4519
|
+
if (sub === 'record-failure') {
|
|
4520
|
+
const flags = parseScopedSyncFlags(rest, { booleans: ['--mutation-not-applied'], values: ['--database', '--key', '--op', '--plan-hash', '--error-code', '--error-message'] });
|
|
4521
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4522
|
+
if (!flags.database || !flags.key || !flags.op || !flags.planHash || !flags.errorCode) {
|
|
4523
|
+
throw new Error('Usage: veycraft career sync record-failure --database <db> --key <key> --op <op_id> --plan-hash <64hex> --error-code <code> [--error-message <msg>] [--mutation-not-applied] [--json]');
|
|
4524
|
+
}
|
|
4525
|
+
const res = recordSyncFailure(root, {
|
|
4526
|
+
database: flags.database,
|
|
4527
|
+
canonicalKey: flags.key,
|
|
4528
|
+
operationId: flags.op,
|
|
4529
|
+
approvedPlanHash: flags.planHash,
|
|
4530
|
+
errorCode: flags.errorCode,
|
|
4531
|
+
errorMessage: flags.errorMessage || null,
|
|
4532
|
+
mutationNotApplied: Boolean(flags.mutationNotApplied),
|
|
4533
|
+
nowIso,
|
|
4534
|
+
home,
|
|
4535
|
+
});
|
|
4536
|
+
const lines = [
|
|
4537
|
+
`Recorded Failure: ${res.state_key} -> ${res.state} (${res.classification}, retries=${res.retry_count})`,
|
|
4538
|
+
...(res.next_retry_after ? [`Next Retry After: ${res.next_retry_after}`] : []),
|
|
4539
|
+
];
|
|
4540
|
+
return { json: flags.json, exitCode: 0, data: res, lines };
|
|
4541
|
+
}
|
|
4542
|
+
|
|
4543
|
+
if (sub === 'expire-stale') {
|
|
4544
|
+
const flags = parseScopedSyncFlags(rest, { values: ['--timeout-minutes'] });
|
|
4545
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4546
|
+
let staleTimeoutMs = DEFAULT_STALE_IN_FLIGHT_TIMEOUT_MS;
|
|
4547
|
+
if (flags.timeoutMinutes !== undefined) {
|
|
4548
|
+
const mins = Number(flags.timeoutMinutes);
|
|
4549
|
+
if (!Number.isSafeInteger(mins) || mins < 1) {
|
|
4550
|
+
throw new Error('--timeout-minutes must be a positive integer.');
|
|
4551
|
+
}
|
|
4552
|
+
staleTimeoutMs = mins * 60 * 1000;
|
|
4553
|
+
}
|
|
4554
|
+
const res = expireStaleInFlightRecords(root, { nowIso, staleTimeoutMs, home });
|
|
4555
|
+
const lines = [
|
|
4556
|
+
`Expired Stale Ops: ${res.expired_count} record(s) moved to receipt_uncertain`,
|
|
4557
|
+
...(res.expired_keys.length > 0 ? [`Expired Keys: ${res.expired_keys.join(', ')}`] : []),
|
|
4558
|
+
];
|
|
4559
|
+
return { json: flags.json, exitCode: 0, data: res, lines };
|
|
4560
|
+
}
|
|
4561
|
+
|
|
4562
|
+
if (sub === 'reconcile') {
|
|
4563
|
+
const flags = parseScopedSyncFlags(rest, { booleans: ['--confirm-remote-deleted'], values: ['--database', '--key', '--database-id', '--file'] });
|
|
4564
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4565
|
+
if (!flags.database || !flags.key || !flags.databaseId || !flags.file) {
|
|
4566
|
+
throw new Error('Usage: veycraft career sync reconcile --database <db> --key <key> --database-id <uuid> --file <snapshot.json> [--confirm-remote-deleted] [--json]');
|
|
4567
|
+
}
|
|
4568
|
+
const snapshot = readSyncCliJsonFile(flags.file, { root, home });
|
|
4569
|
+
const res = reconcileSyncRecord(root, {
|
|
4570
|
+
database: flags.database,
|
|
4571
|
+
canonicalKey: flags.key,
|
|
4572
|
+
expectedDatabaseId: flags.databaseId,
|
|
4573
|
+
querySnapshot: snapshot,
|
|
4574
|
+
confirmRemotePageDeleted: Boolean(flags.confirmRemoteDeleted),
|
|
4575
|
+
nowIso,
|
|
4576
|
+
home,
|
|
4577
|
+
});
|
|
4578
|
+
const lines = [
|
|
4579
|
+
`Reconciliation: ${res.state_key} -> ${res.state} (${res.resolution})`,
|
|
4580
|
+
];
|
|
4581
|
+
return { json: flags.json, exitCode: res.reconciled ? 0 : 1, data: res, lines };
|
|
4582
|
+
}
|
|
4583
|
+
|
|
4584
|
+
if (sub === 'reset-permanent') {
|
|
4585
|
+
const flags = parseScopedSyncFlags(rest, { booleans: ['--confirm-reset'], values: ['--database', '--key', '--expected-error', '--reason'] });
|
|
4586
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4587
|
+
if (!flags.database || !flags.key || flags.expectedError === undefined || !flags.reason) {
|
|
4588
|
+
throw new Error('Usage: veycraft career sync reset-permanent --database <db> --key <key> --expected-error <err|null> --reason <text> --confirm-reset [--json]');
|
|
4589
|
+
}
|
|
4590
|
+
const expectedLastError = flags.expectedError === 'null' ? null : flags.expectedError;
|
|
4591
|
+
const res = resetPermanentFailure(root, {
|
|
4592
|
+
database: flags.database,
|
|
4593
|
+
canonicalKey: flags.key,
|
|
4594
|
+
expectedLastError,
|
|
4595
|
+
resetReason: flags.reason,
|
|
4596
|
+
confirmedByOwner: Boolean(flags.confirmReset),
|
|
4597
|
+
nowIso,
|
|
4598
|
+
home,
|
|
4599
|
+
});
|
|
4600
|
+
const lines = [
|
|
4601
|
+
`Reset Permanent: ${res.state_key} -> ${res.state} (cleared: ${res.previous_error ?? 'null'})`,
|
|
4602
|
+
];
|
|
4603
|
+
return { json: flags.json, exitCode: 0, data: res, lines };
|
|
4604
|
+
}
|
|
4605
|
+
|
|
4606
|
+
if (sub === 'release-stale-lock') {
|
|
4607
|
+
const flags = parseScopedSyncFlags(rest, { booleans: ['--confirm-unlock'], values: ['--nonce'] });
|
|
4608
|
+
if (flags.help) return { json: false, exitCode: 0, data: {}, lines: formatCareerSyncHelp() };
|
|
4609
|
+
if (!flags.nonce) {
|
|
4610
|
+
throw new Error('Usage: veycraft career sync release-stale-lock --nonce <nonce> --confirm-unlock [--json]');
|
|
4611
|
+
}
|
|
4612
|
+
const res = releaseStaleSyncStateLock(root, {
|
|
4613
|
+
home,
|
|
4614
|
+
nowIso,
|
|
4615
|
+
expectedNonce: flags.nonce,
|
|
4616
|
+
confirmedExplicitRecovery: Boolean(flags.confirmUnlock),
|
|
4617
|
+
});
|
|
4618
|
+
const lines = [
|
|
4619
|
+
`Released Stale Lock: ${res.path} (dead PID=${res.released_pid})`,
|
|
4620
|
+
];
|
|
4621
|
+
return { json: flags.json, exitCode: 0, data: res, lines };
|
|
4622
|
+
}
|
|
4623
|
+
|
|
4624
|
+
throw new Error(`Unknown career sync subcommand "${sub}". Supported: ${CAREER_SYNC_SUBCOMMANDS.join(', ')}.`);
|
|
4625
|
+
}
|