/**
 * Phase 1 — orphan detection.
 *
 * Finds semantic-entity nodes for this account with zero inbound edges of
 * any type (`MENTIONS`, `HAS_SECTION`, `PARTY`, `AT`, `UNDER`,
 * `HAS_POSITION`, etc.). Writes one `:OrphanCandidate` per orphan with a
 * pointer back via `targetElementId`; existing candidate rows are MERGEd
 * so re-running does not duplicate.
 *
 * Scope: `:Person`, `:Organization`, `:Concept`, `:Project`. Not
 * `:Section`, `:Message`, `:Conversation`, `:KnowledgeDocument`, `:ConversationArchive`, `:Event`
 * — those are structurally anchored (a Section's `HAS_SECTION` arrow is
 * its life; auditing it for inbound edges is not signal).
 *
 * `:Trashed` nodes are skipped — they are already soft-deleted.
 */
import { randomUUID } from "node:crypto";
const ORPHAN_LABELS = ["Person", "Organization", "Concept", "Project"];
export async function phaseOrphans(ctx) {
    const start = Date.now();
    const { accountId, session } = ctx;
    let proposed = 0;
    for (const label of ORPHAN_LABELS) {
        const result = await session.run(`MATCH (n:${label})
       WHERE n.accountId = $accountId
         AND NOT n:Trashed
         AND NOT (n)<--()
       WITH n, elementId(n) AS targetElementId, labels(n) AS targetLabels
       MERGE (o:OrphanCandidate {accountId: $accountId, targetElementId: targetElementId})
       ON CREATE SET o.orphanCandidateId = $newId,
                     o.targetLabel = $label,
                     o.targetName = coalesce(n.name, n.title, '<unnamed>'),
                     o.since = datetime(),
                     o.createdAt = datetime()
       RETURN count(o) AS proposed`, { accountId, label, newId: randomUUID() });
        proposed += Number(result.records[0]?.get("proposed") ?? 0);
    }
    const durationSec = Math.round((Date.now() - start) / 1000);
    process.stderr.write(`[dream-cycle:phase-1] durationSec=${durationSec} proposed=${proposed} applied=0 deferred=${proposed}\n`);
    return { phase: 1, name: "orphans", durationSec, proposed, applied: 0, deferred: proposed };
}
//# sourceMappingURL=phase-orphans.js.map