Compare commits
17 Commits
chore/618-
...
f0925982c9
| Author | SHA1 | Date | |
|---|---|---|---|
| f0925982c9 | |||
| cfbeb582fa | |||
| 4550c4132a | |||
| 294833ccc5 | |||
| f48579d574 | |||
| c5a605ab1d | |||
| 517b3ee844 | |||
| 75aa931f85 | |||
| 2d4113e581 | |||
| e324240b7e | |||
| 68f85717de | |||
| 50b29d4b12 | |||
| f3b972119b | |||
| c79a7a0b9f | |||
| 2a6165ac86 | |||
| c51f8c36e7 | |||
| 5a5fdd9162 |
73
src/comment-routing.test.ts
Normal file
73
src/comment-routing.test.ts
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
/// <reference types="node" />
|
||||||
|
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import {
|
||||||
|
CLOSED_ISSUE_STATUSES,
|
||||||
|
nativeWakeCoversComment,
|
||||||
|
} from "./comment-routing.ts";
|
||||||
|
|
||||||
|
const CEO = "cdbfa8bc-3d61-41a4-a2e7-677ec7d34562";
|
||||||
|
const ANALYST = "752cebdd-6748-4a04-aacd-c7ab0294ef33";
|
||||||
|
|
||||||
|
// ── #16 AC: issue פתוח משויך-CEO, בלי reopened → הנייטיבי מכסה, אין invoke ──
|
||||||
|
test("open CEO-owned issue is covered natively (the #772 / CMPA-232 case)", () => {
|
||||||
|
for (const status of ["in_progress", "in_review", "todo", "blocked"]) {
|
||||||
|
assert.equal(
|
||||||
|
nativeWakeCoversComment({ status, assigneeAgentId: CEO }),
|
||||||
|
true,
|
||||||
|
status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// הכלל הוא "משויך לסוכן", לא "משויך ל-CEO": Paperclip מעיר כל assignee-סוכן.
|
||||||
|
test("open issue owned by any agent is covered natively", () => {
|
||||||
|
assert.equal(
|
||||||
|
nativeWakeCoversComment({
|
||||||
|
status: "in_progress",
|
||||||
|
assigneeAgentId: ANALYST,
|
||||||
|
}),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── #16 AC: משויך לאדם / לא משויך → הנייטיבי מת → חובה לנתב ──
|
||||||
|
test("human-owned or unassigned open issue is NOT covered → plugin must route", () => {
|
||||||
|
assert.equal(
|
||||||
|
nativeWakeCoversComment({ status: "in_review", assigneeAgentId: null }),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
nativeWakeCoversComment({
|
||||||
|
status: "in_review",
|
||||||
|
assigneeAgentId: undefined,
|
||||||
|
}),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
nativeWakeCoversComment({ status: "in_review", assigneeAgentId: "" }),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── סגור → Paperclip מדלג על ה-wakeup גם כשיש assignee-סוכן ──
|
||||||
|
test("closed issue is never covered natively, whoever owns it", () => {
|
||||||
|
for (const status of CLOSED_ISSUE_STATUSES) {
|
||||||
|
assert.equal(
|
||||||
|
nativeWakeCoversComment({ status, assigneeAgentId: CEO }),
|
||||||
|
false,
|
||||||
|
status,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
nativeWakeCoversComment({ status, assigneeAgentId: null }),
|
||||||
|
false,
|
||||||
|
status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// מראה של legal-ai `CLOSED_ISSUE_STATUSES` — שינוי שם מחייב שינוי כאן.
|
||||||
|
test("closed statuses mirror legal-ai needs_ceo_run()", () => {
|
||||||
|
assert.deepEqual([...CLOSED_ISSUE_STATUSES].sort(), ["cancelled", "done"]);
|
||||||
|
});
|
||||||
43
src/comment-routing.ts
Normal file
43
src/comment-routing.ts
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
/**
|
||||||
|
* מסלול-יקיצה יחיד להערת-יו"ר (plugin-legal-ai #16, legal-ai #772).
|
||||||
|
*
|
||||||
|
* Paperclip מעיר **בעצמו** את הסוכן המשויך ל-issue על כל הערת-משתמש
|
||||||
|
* (`@paperclipai/server` routes/issues.js — `addWakeup(assigneeId, {reason:
|
||||||
|
* "issue_commented", payload.mutation: "comment"})`), ובלבד ש-(א) יש assignee-סוכן,
|
||||||
|
* (ב) ה-issue אינו סגור (`done`/`cancelled`), (ג) ההערה אינה של אותו סוכן עצמו.
|
||||||
|
* `ctx.agents.invoke` של הפלאגין על אותה הערה = ריצת-CEO שנייה במקביל: עבודה
|
||||||
|
* כפולה, שתי רשומות `chair_feedback`, שני issues לכותב (legal-ai #772; שוב
|
||||||
|
* 2026-11-01 על CMPA-232 — 3 ריצות כפולות, ~9$).
|
||||||
|
*
|
||||||
|
* ⚠️ מקור-האמת לכלל הוא **`needs_ceo_run()` ב-legal-ai `web/paperclip_client.py`**
|
||||||
|
* (נמדד על 120 יום ב-DB החי: agent-owned + open → 70/70 הערות קיבלו wakeup נייטיבי;
|
||||||
|
* human-owned/unassigned → ה-wakeup מכוון לאדם ומבוטל; closed → אין wakeup כלל).
|
||||||
|
* הפונקציה כאן היא **מראה** של אותו כלל בצד הפלאגין — אין דרך לקרוא ל-legal-ai
|
||||||
|
* מתוך event-handler בלי להוסיף תלות-רשת לנתיב-המסירה. **כל שינוי שם מחייב
|
||||||
|
* שינוי כאן**, ולהיפך (G2 — מסלול-החלטה אחד, שני מימושים שחייבים להישאר זהים).
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** סטטוסים סופיים — Paperclip מדלג על ה-wakeup הנייטיבי בהם (`isClosed`). */
|
||||||
|
export const CLOSED_ISSUE_STATUSES: ReadonlySet<string> = new Set([
|
||||||
|
"done",
|
||||||
|
"cancelled",
|
||||||
|
]);
|
||||||
|
|
||||||
|
export interface RoutableIssue {
|
||||||
|
status: string;
|
||||||
|
assigneeAgentId?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* האם המסירה הנייטיבית של Paperclip כבר מעירה סוכן על הערה ב-issue הזה?
|
||||||
|
*
|
||||||
|
* `true` → **אין** להפעיל `ctx.agents.invoke` (זה יהיה המסלול הכפול).
|
||||||
|
* `false` → המסלול הנייטיבי מת (issue סגור, או משויך לאדם / לא משויך) — זו
|
||||||
|
* בדיוק הסיבה שמסלול-הפלאגין קיים (#164/#454), ויש לנתב ל-CEO.
|
||||||
|
*
|
||||||
|
* זהה ל-`not needs_ceo_run(issue)` ב-legal-ai.
|
||||||
|
*/
|
||||||
|
export function nativeWakeCoversComment(issue: RoutableIssue): boolean {
|
||||||
|
if (CLOSED_ISSUE_STATUSES.has(issue.status)) return false;
|
||||||
|
return Boolean(issue.assigneeAgentId);
|
||||||
|
}
|
||||||
138
src/devil-closer.test.ts
Normal file
138
src/devil-closer.test.ts
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
/// <reference types="node" />
|
||||||
|
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
import {
|
||||||
|
type CloseDeps,
|
||||||
|
caseNumberFromTitle,
|
||||||
|
closeDevilIssueIfDone,
|
||||||
|
DEVIL_AGENT_IDS,
|
||||||
|
} from "./devil-closer.ts";
|
||||||
|
|
||||||
|
const CMPA = "8639e837-4c9d-47fa-a76b-95788d651896";
|
||||||
|
const DEVIL = DEVIL_AGENT_IDS[CMPA];
|
||||||
|
const TITLE = "[ערר 8165-11-25] שטן-מליץ — red-team על הניתוח";
|
||||||
|
|
||||||
|
function deps(over: Partial<CloseDeps> = {}) {
|
||||||
|
const closed: string[] = [];
|
||||||
|
const d: CloseDeps = {
|
||||||
|
getIssue: async (id) => ({
|
||||||
|
id,
|
||||||
|
title: TITLE,
|
||||||
|
status: "in_progress",
|
||||||
|
assigneeAgentId: DEVIL,
|
||||||
|
createdAt: "2026-10-14T12:45:58Z",
|
||||||
|
}),
|
||||||
|
statCritique: async () => ({
|
||||||
|
size: 39261,
|
||||||
|
mtimeMs: Date.parse("2026-10-14T13:29:50Z"),
|
||||||
|
}),
|
||||||
|
closeIssue: async (id) => {
|
||||||
|
closed.push(id);
|
||||||
|
},
|
||||||
|
log: () => {},
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
return { d, closed };
|
||||||
|
}
|
||||||
|
|
||||||
|
const RUN = { agentId: DEVIL, issueId: "i1", status: "succeeded" };
|
||||||
|
|
||||||
|
test("caseNumberFromTitle", () => {
|
||||||
|
assert.equal(caseNumberFromTitle(TITLE), "8165-11-25");
|
||||||
|
assert.equal(caseNumberFromTitle("[ערר 8027/25] x"), "8027/25");
|
||||||
|
assert.equal(caseNumberFromTitle("בלי מספר"), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("סוגר כשהכול תקין", async () => {
|
||||||
|
const { d, closed } = deps();
|
||||||
|
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "closed");
|
||||||
|
assert.deepEqual(closed, ["i1"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("לא סוכן שטן → לא נוגע", async () => {
|
||||||
|
const { d, closed } = deps();
|
||||||
|
assert.equal(
|
||||||
|
await closeDevilIssueIfDone(CMPA, { ...RUN, agentId: "other" }, d),
|
||||||
|
"not_devil_run",
|
||||||
|
);
|
||||||
|
assert.equal(closed.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("חברה לא מוכרת → לא נוגע", async () => {
|
||||||
|
const { d } = deps();
|
||||||
|
assert.equal(await closeDevilIssueIfDone("nope", RUN, d), "not_devil_run");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("ריצה שלא הצליחה → לא סוגר", async () => {
|
||||||
|
const { d, closed } = deps();
|
||||||
|
assert.equal(
|
||||||
|
await closeDevilIssueIfDone(CMPA, { ...RUN, status: "failed" }, d),
|
||||||
|
"not_devil_run",
|
||||||
|
);
|
||||||
|
assert.equal(closed.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("issue שאינו של שטן (כותרת אחרת) → לא סוגר", async () => {
|
||||||
|
const { d, closed } = deps({
|
||||||
|
getIssue: async (id) => ({
|
||||||
|
id,
|
||||||
|
title: "[ערר 1-1-1] ניתוח משפטי",
|
||||||
|
status: "in_progress",
|
||||||
|
assigneeAgentId: DEVIL,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "not_devil_issue");
|
||||||
|
assert.equal(closed.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("כבר סגור → לא סוגר שוב", async () => {
|
||||||
|
const { d, closed } = deps({
|
||||||
|
getIssue: async (id) => ({
|
||||||
|
id,
|
||||||
|
title: TITLE,
|
||||||
|
status: "done",
|
||||||
|
assigneeAgentId: DEVIL,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "already_closed");
|
||||||
|
assert.equal(closed.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("אין קובץ מזכר → נשאר פתוח", async () => {
|
||||||
|
const { d, closed } = deps({ statCritique: async () => null });
|
||||||
|
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "no_deliverable");
|
||||||
|
assert.equal(closed.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("קובץ ישן מלפני יצירת ה-issue → נשאר פתוח", async () => {
|
||||||
|
const { d, closed } = deps({
|
||||||
|
statCritique: async () => ({
|
||||||
|
size: 39261,
|
||||||
|
mtimeMs: Date.parse("2026-10-01T00:00:00Z"),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "no_deliverable");
|
||||||
|
assert.equal(closed.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("קובץ קצר מדי → נשאר פתוח", async () => {
|
||||||
|
const { d, closed } = deps({
|
||||||
|
statCritique: async () => ({
|
||||||
|
size: 300,
|
||||||
|
mtimeMs: Date.parse("2026-10-14T13:29:50Z"),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "no_deliverable");
|
||||||
|
assert.equal(closed.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("כשל גישה לקובץ → נשאר פתוח (fail-safe)", async () => {
|
||||||
|
const { d, closed } = deps({
|
||||||
|
statCritique: async () => {
|
||||||
|
throw new Error("EACCES");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
assert.equal(await closeDevilIssueIfDone(CMPA, RUN, d), "stat_failed");
|
||||||
|
assert.equal(closed.length, 0);
|
||||||
|
});
|
||||||
142
src/devil-closer.ts
Normal file
142
src/devil-closer.ts
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
/**
|
||||||
|
* סגירה אוטומטית של issue "שטן-מליץ" אחרי ריצה מוצלחת (legal-ai #892).
|
||||||
|
*
|
||||||
|
* הרקע: סוכן Gemini רץ בלי shell (#872) ולכן אינו יכול לסגור את ה-issue שלו.
|
||||||
|
* Paperclip מעיר את ה-CEO רק על `issue_children_completed` (ילד ב-`done`), ו-issue
|
||||||
|
* שנשאר פתוח עובר ל-`blocked` ("successful run missing disposition") — וה-CEO אינו
|
||||||
|
* מתעורר לעולם (אין לו heartbeat מחזורי). התוצאה בתיק 8165-11-25: המזכר נכתב והתהליך נתקע.
|
||||||
|
*
|
||||||
|
* הלוגיקה כאן טהורה (תלויות מוזרקות) כדי שאפשר לבדוק אותה בלי host.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** חברה → agent id של שטן-מליץ באותה חברה (Fable מאז legal-ai #978; היה Gemini). */
|
||||||
|
export const DEVIL_AGENT_IDS: Record<string, string> = {
|
||||||
|
"42a7acd0-30c5-4cbd-ac97-7424f65df294":
|
||||||
|
"9c86e06a-5a92-4723-af6d-e8cc6ae1d45b", // CMP
|
||||||
|
"8639e837-4c9d-47fa-a76b-95788d651896":
|
||||||
|
"46cc1228-a232-410b-a36b-71a6928499a2", // CMPA
|
||||||
|
};
|
||||||
|
|
||||||
|
/** קובץ המזכר: critique.md (Fable, legal-ai #978); critique-gemini.md לתיקים שרצו לפני המעבר. */
|
||||||
|
export const CRITIQUE_FILENAMES = [
|
||||||
|
"critique.md",
|
||||||
|
"critique-gemini.md",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const DEFAULT_CASES_DIR = "/home/chaim/legal-ai/data/cases";
|
||||||
|
/** מזכר קצר מזה = כנראה ריצה ריקה/חלקית, לא סוגרים. */
|
||||||
|
export const MIN_CRITIQUE_BYTES = 2000;
|
||||||
|
|
||||||
|
const CLOSED = new Set(["done", "cancelled"]);
|
||||||
|
|
||||||
|
export interface DevilIssueLike {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
status: string;
|
||||||
|
assigneeAgentId?: string | null;
|
||||||
|
createdAt?: string | Date | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DevilRunPayload {
|
||||||
|
agentId?: string;
|
||||||
|
issueId?: string | null;
|
||||||
|
status?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CloseDeps {
|
||||||
|
getIssue(issueId: string, companyId: string): Promise<DevilIssueLike | null>;
|
||||||
|
/** גודל + זמן-שינוי של הקובץ, או null אם אינו קיים. זורק רק על כשל-גישה. */
|
||||||
|
statCritique(
|
||||||
|
caseNumber: string,
|
||||||
|
): Promise<{ size: number; mtimeMs: number } | null>;
|
||||||
|
closeIssue(issueId: string, companyId: string): Promise<void>;
|
||||||
|
log(
|
||||||
|
level: "info" | "warn",
|
||||||
|
msg: string,
|
||||||
|
meta?: Record<string, unknown>,
|
||||||
|
): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function caseNumberFromTitle(title: string): string | null {
|
||||||
|
const m = title.match(/\[ערר\s+([^\]\s]+)\]/);
|
||||||
|
return m ? m[1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isDevilTitle(title: string): boolean {
|
||||||
|
return title.includes("שטן-מליץ");
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CloseOutcome =
|
||||||
|
| "closed"
|
||||||
|
| "not_devil_run"
|
||||||
|
| "no_issue"
|
||||||
|
| "not_devil_issue"
|
||||||
|
| "already_closed"
|
||||||
|
| "no_case_number"
|
||||||
|
| "no_deliverable"
|
||||||
|
| "stat_failed";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* מופעל על `agent.run.finished` (status=succeeded בלבד). סוגר את ה-issue רק אם:
|
||||||
|
* הריצה של שטן-מליץ של אותה חברה, ה-issue שלו פתוח, וקיים מזכר (`critique.md`) עדכני ולא ריק.
|
||||||
|
*/
|
||||||
|
export async function closeDevilIssueIfDone(
|
||||||
|
companyId: string | undefined,
|
||||||
|
payload: DevilRunPayload | null,
|
||||||
|
deps: CloseDeps,
|
||||||
|
): Promise<CloseOutcome> {
|
||||||
|
if (!companyId || !payload) return "not_devil_run";
|
||||||
|
const devilId = DEVIL_AGENT_IDS[companyId];
|
||||||
|
if (!devilId || payload.agentId !== devilId) return "not_devil_run";
|
||||||
|
if (payload.status && payload.status !== "succeeded") return "not_devil_run";
|
||||||
|
if (!payload.issueId) return "no_issue";
|
||||||
|
|
||||||
|
const issue = await deps.getIssue(payload.issueId, companyId);
|
||||||
|
if (!issue) return "no_issue";
|
||||||
|
if (issue.assigneeAgentId !== devilId || !isDevilTitle(issue.title)) {
|
||||||
|
return "not_devil_issue";
|
||||||
|
}
|
||||||
|
if (CLOSED.has(issue.status)) return "already_closed";
|
||||||
|
|
||||||
|
const caseNumber = caseNumberFromTitle(issue.title);
|
||||||
|
if (!caseNumber) return "no_case_number";
|
||||||
|
|
||||||
|
let st: { size: number; mtimeMs: number } | null;
|
||||||
|
try {
|
||||||
|
st = await deps.statCritique(caseNumber);
|
||||||
|
} catch {
|
||||||
|
deps.log(
|
||||||
|
"warn",
|
||||||
|
"devil auto-close: critique stat failed; leaving issue open",
|
||||||
|
{
|
||||||
|
issueId: issue.id,
|
||||||
|
caseNumber,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return "stat_failed";
|
||||||
|
}
|
||||||
|
const created = issue.createdAt ? new Date(issue.createdAt).getTime() : 0;
|
||||||
|
if (!st || st.size < MIN_CRITIQUE_BYTES || st.mtimeMs < created) {
|
||||||
|
deps.log(
|
||||||
|
"warn",
|
||||||
|
"devil auto-close: no fresh critique memo; leaving issue open",
|
||||||
|
{
|
||||||
|
issueId: issue.id,
|
||||||
|
caseNumber,
|
||||||
|
size: st?.size ?? null,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return "no_deliverable";
|
||||||
|
}
|
||||||
|
|
||||||
|
await deps.closeIssue(issue.id, companyId);
|
||||||
|
deps.log(
|
||||||
|
"info",
|
||||||
|
"devil auto-close: issue closed (CEO is woken by issue_children_completed)",
|
||||||
|
{
|
||||||
|
issueId: issue.id,
|
||||||
|
caseNumber,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return "closed";
|
||||||
|
}
|
||||||
@@ -36,6 +36,15 @@ export class LegalApi {
|
|||||||
return this.request("/api/cases");
|
return this.request("/api/cases");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal `{case_number, status}` index for `sync-case-status` (legal-ai #1117).
|
||||||
|
* Lives on the internal machine route; the fuller `/api/cases` listing does not
|
||||||
|
* (session-only), so the sync job must not call `listCases()`.
|
||||||
|
*/
|
||||||
|
async listCaseStatuses(): Promise<CaseStatusEntry[]> {
|
||||||
|
return this.request("/api/cases/status-index");
|
||||||
|
}
|
||||||
|
|
||||||
async getStatusModel(): Promise<StatusModel> {
|
async getStatusModel(): Promise<StatusModel> {
|
||||||
return this.request("/api/status-model");
|
return this.request("/api/status-model");
|
||||||
}
|
}
|
||||||
@@ -182,6 +191,12 @@ export class LegalApi {
|
|||||||
|
|
||||||
// Types
|
// Types
|
||||||
|
|
||||||
|
export interface CaseStatusEntry {
|
||||||
|
case_number: string;
|
||||||
|
status: string;
|
||||||
|
updated_at?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface CaseSummary {
|
export interface CaseSummary {
|
||||||
case_number: string;
|
case_number: string;
|
||||||
title: string;
|
title: string;
|
||||||
|
|||||||
@@ -179,19 +179,13 @@ export default {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
jobs: [
|
jobs: [
|
||||||
{
|
// הושבת (legal-ai #1117, INV-INT9 — כותב יחיד ל-issue.status): הסנכרון עבר
|
||||||
jobKey: "sync-case-status",
|
// לצד-השרת (`_case_status_sync_loop` ב-legal-ai, CASE_STATUS_SYNC_MODE).
|
||||||
displayName: "Sync Legal Case Status",
|
// הסרה מההצהרה גורמת ל-Paperclip להעביר את הג'וב ל-`paused` בהתקנה הבאה.
|
||||||
description:
|
// ה-handler ב-worker.ts נשאר רשום אך לא יופעל.
|
||||||
"Polls legal-ai for case status changes and updates Paperclip issues",
|
// הושבת (legal-ai #1117, הוראת חיים): תיק ללא תנועה לעיתים הוא מכוון, והתזכורות
|
||||||
schedule: "*/15 * * * *",
|
// היו רעש בלבד. הסרה מההצהרה => Paperclip מעביר ל-`paused` בהתקנה הבאה.
|
||||||
},
|
// ה-handler ב-worker.ts נשאר רשום אך לא יופעל.
|
||||||
{
|
|
||||||
jobKey: "stale-case-reminder",
|
|
||||||
displayName: "תזכורת תיקים תקועים",
|
|
||||||
description: "מזהה תיקים שלא עודכנו 30+ ימים ומוסיף תגובה ל-issue",
|
|
||||||
schedule: "0 8 * * *",
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
jobKey: "weekly-feedback-analysis",
|
jobKey: "weekly-feedback-analysis",
|
||||||
displayName: "ניתוח פידבק שבועי",
|
displayName: "ניתוח פידבק שבועי",
|
||||||
|
|||||||
24
src/worker-fetch.test.ts
Normal file
24
src/worker-fetch.test.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
/// <reference types="node" />
|
||||||
|
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { test } from "node:test";
|
||||||
|
// Excluded from tsc (tsconfig.json), run natively via `node --test` (literal `.ts`).
|
||||||
|
import { fetchLegalApi } from "./worker-fetch.ts";
|
||||||
|
|
||||||
|
test("fetchLegalApi uses the worker's global fetch (not the host-mediated ctx.http.fetch)", async () => {
|
||||||
|
const original = globalThis.fetch;
|
||||||
|
let called = "";
|
||||||
|
globalThis.fetch = (async (url: string) => {
|
||||||
|
called = url;
|
||||||
|
return new Response("{}", { status: 200 });
|
||||||
|
}) as typeof fetch;
|
||||||
|
try {
|
||||||
|
const resp = await fetchLegalApi(
|
||||||
|
"http://127.0.0.1:8001/api/cases/stale?days=30",
|
||||||
|
);
|
||||||
|
assert.equal(resp.ok, true);
|
||||||
|
assert.equal(called, "http://127.0.0.1:8001/api/cases/stale?days=30");
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = original;
|
||||||
|
}
|
||||||
|
});
|
||||||
16
src/worker-fetch.ts
Normal file
16
src/worker-fetch.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* `fetch` of the worker process — used by the scheduled jobs that read legal-ai's
|
||||||
|
* internal-machine routes at `http://127.0.0.1:8001`. `ctx.http.fetch` is host-mediated
|
||||||
|
* and Paperclip's SSRF guard rejects loopback/private targets ("All resolved IPs for
|
||||||
|
* 127.0.0.1 are in private/reserved ranges"), which is why `stale-case-reminder` and
|
||||||
|
* `weekly-feedback-analysis` failed (legal-ai #1117). `LegalApi` already uses this fetch.
|
||||||
|
*
|
||||||
|
* Kept in its own module (no TypeScript parameter properties) so `node --test` can
|
||||||
|
* load it in strip-only mode.
|
||||||
|
*/
|
||||||
|
export function fetchLegalApi(
|
||||||
|
url: string,
|
||||||
|
init?: RequestInit,
|
||||||
|
): Promise<Response> {
|
||||||
|
return fetch(url, init);
|
||||||
|
}
|
||||||
109
src/worker.ts
109
src/worker.ts
@@ -1,8 +1,12 @@
|
|||||||
|
/// <reference types="node" />
|
||||||
|
|
||||||
|
import { stat } from "node:fs/promises";
|
||||||
import type {
|
import type {
|
||||||
PluginContext,
|
PluginContext,
|
||||||
PluginWebhookInput,
|
PluginWebhookInput,
|
||||||
} from "@paperclipai/plugin-sdk";
|
} from "@paperclipai/plugin-sdk";
|
||||||
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
|
import { definePlugin, runWorker } from "@paperclipai/plugin-sdk";
|
||||||
|
import { nativeWakeCoversComment } from "./comment-routing.js";
|
||||||
import {
|
import {
|
||||||
CompanyScopeUnavailableError,
|
CompanyScopeUnavailableError,
|
||||||
isCompanyScopeDenied,
|
isCompanyScopeDenied,
|
||||||
@@ -10,6 +14,11 @@ import {
|
|||||||
resolveApiBaseFrom,
|
resolveApiBaseFrom,
|
||||||
runJobHandler,
|
runJobHandler,
|
||||||
} from "./company-scope.js";
|
} from "./company-scope.js";
|
||||||
|
import {
|
||||||
|
CRITIQUE_FILENAMES,
|
||||||
|
closeDevilIssueIfDone,
|
||||||
|
DEFAULT_CASES_DIR,
|
||||||
|
} from "./devil-closer.js";
|
||||||
import type { StatusModelEntry } from "./legal-api.js";
|
import type { StatusModelEntry } from "./legal-api.js";
|
||||||
import { LegalApi } from "./legal-api.js";
|
import { LegalApi } from "./legal-api.js";
|
||||||
import {
|
import {
|
||||||
@@ -27,6 +36,7 @@ import {
|
|||||||
resolveStatusLabel,
|
resolveStatusLabel,
|
||||||
type SyncCandidate,
|
type SyncCandidate,
|
||||||
} from "./sync-target.js";
|
} from "./sync-target.js";
|
||||||
|
import { fetchLegalApi } from "./worker-fetch.js";
|
||||||
|
|
||||||
// Hoisted so onWebhook can access the context after setup() completes.
|
// Hoisted so onWebhook can access the context after setup() completes.
|
||||||
let pluginCtx: PluginContext | null = null;
|
let pluginCtx: PluginContext | null = null;
|
||||||
@@ -739,6 +749,63 @@ const plugin = definePlugin({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── שטן-מליץ: סגירה אוטומטית אחרי ריצה מוצלחת (legal-ai #892) ──
|
||||||
|
// הסוכן רץ בלי shell ולכן אינו יכול לסגור את ה-issue שלו; בלי `done` ה-CEO
|
||||||
|
// לעולם לא מתעורר (`issue_children_completed`). ראה devil-closer.ts.
|
||||||
|
ctx.events.on("agent.run.finished", async (event) => {
|
||||||
|
try {
|
||||||
|
const casesDir = process.env.LEGAL_AI_CASES_DIR || DEFAULT_CASES_DIR;
|
||||||
|
await closeDevilIssueIfDone(
|
||||||
|
event.companyId,
|
||||||
|
(event.payload ?? null) as Parameters<
|
||||||
|
typeof closeDevilIssueIfDone
|
||||||
|
>[1],
|
||||||
|
{
|
||||||
|
getIssue: async (id, companyId) => {
|
||||||
|
const i = await ctx.issues.get(id, companyId);
|
||||||
|
return i
|
||||||
|
? {
|
||||||
|
id: i.id,
|
||||||
|
title: i.title,
|
||||||
|
status: i.status,
|
||||||
|
assigneeAgentId: i.assigneeAgentId,
|
||||||
|
createdAt: i.createdAt,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
},
|
||||||
|
statCritique: async (caseNumber) => {
|
||||||
|
// critique.md = שטן מליץ על Fable (legal-ai #978); critique-gemini.md = תיקים ישנים.
|
||||||
|
for (const name of CRITIQUE_FILENAMES) {
|
||||||
|
try {
|
||||||
|
const st = await stat(
|
||||||
|
`${casesDir}/${caseNumber}/documents/research/${name}`,
|
||||||
|
);
|
||||||
|
return { size: st.size, mtimeMs: st.mtimeMs };
|
||||||
|
} catch (err) {
|
||||||
|
if ((err as NodeJS.ErrnoException).code !== "ENOENT")
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
// סטטוס בלבד, בלי comment: comment מעיר את ה-CEO פעם שנייה (user_commented).
|
||||||
|
closeIssue: async (id, companyId) => {
|
||||||
|
// כותב-סטטוס שני וצר בכוונה: רק issue של שטן-מליץ (נבדק בכותרת ובסוכן), רק open→done,
|
||||||
|
// רק אחרי ריצה מוצלחת + מזכר (critique.md) עדכני (devil-closer.ts). בלי זה הסוכן
|
||||||
|
// (בלי shell, #872) לא סוגר והתהליך נתקע; אין flip-flop כי done סופי.
|
||||||
|
// noqa: INT9 — סגירת issue של שטן-מליץ אחרי ריצה מוצלחת (legal-ai #892), ראה devil-closer.ts
|
||||||
|
await ctx.issues.update(id, { status: "done" }, companyId);
|
||||||
|
},
|
||||||
|
log: (level, msg, meta) => ctx.logger[level](msg, meta),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
ctx.logger.warn("devil auto-close handler failed", {
|
||||||
|
error: err instanceof Error ? err.name : "unknown",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
ctx.events.on("issue.comment.created", async (event) => {
|
ctx.events.on("issue.comment.created", async (event) => {
|
||||||
// Only intercept human comments — not agent comments (prevents loops)
|
// Only intercept human comments — not agent comments (prevents loops)
|
||||||
if (event.actorType !== "user") return;
|
if (event.actorType !== "user") return;
|
||||||
@@ -793,17 +860,21 @@ const plugin = definePlugin({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dedup against the host's native reopen-on-comment wake: when a comment
|
// מסלול-יקיצה יחיד (#16, legal-ai #772): Paperclip מעיר בעצמו את הסוכן
|
||||||
// reopens a `done` issue, the host already wakes that issue's assignee.
|
// המשויך על כל הערת-משתמש ב-issue פתוח — לא רק כשההערה פותחת-מחדש issue
|
||||||
// If the assignee IS this company's CEO, that native wake covers us —
|
// סגור (זה היה הכלל הקודם, `reopened === true`, והוא פספס את המקרה הנפוץ:
|
||||||
// invoking again would double-run the CEO. Skip ONLY in that exact case.
|
// issue פתוח ב-`in_review` משויך-CEO → שתי ריצות-CEO במקביל על אותה הערה).
|
||||||
// For issues owned by any other agent (e.g. an analyst sub-task), the
|
// הכלל נגזר מ-`needs_ceo_run()` ב-legal-ai — ראה comment-routing.ts.
|
||||||
// native wake targets the wrong agent (and the queued run is cancelled
|
// הפלאגין מנתב רק במקום שבו הנייטיבי מת: issue סגור, או משויך לאדם / לא משויך.
|
||||||
// with `issue_assignee_changed`), so we MUST route the comment to the CEO.
|
if (nativeWakeCoversComment(issue)) {
|
||||||
if (issue.assigneeAgentId === ceoAgentId && payload?.reopened === true) {
|
|
||||||
ctx.logger.info(
|
ctx.logger.info(
|
||||||
"Comment reopened CEO-owned issue; native wake handles it, skipping plugin route",
|
"Comment on open agent-owned issue; native wake handles it, skipping plugin route (#16)",
|
||||||
{ issueId, ceoAgentId },
|
{
|
||||||
|
issueId,
|
||||||
|
status: issue.status,
|
||||||
|
assigneeAgentId: issue.assigneeAgentId,
|
||||||
|
reopened: payload?.reopened === true,
|
||||||
|
},
|
||||||
);
|
);
|
||||||
// The comment IS being handled (natively) — stamp the marker so the
|
// The comment IS being handled (natively) — stamp the marker so the
|
||||||
// reconciliation sweep does not re-route it a second time.
|
// reconciliation sweep does not re-route it a second time.
|
||||||
@@ -907,7 +978,7 @@ const plugin = definePlugin({
|
|||||||
// כשה-scope נדחה (legal-ai issue #637). ה-`try/catch` הישן כאן בלע
|
// כשה-scope נדחה (legal-ai issue #637). ה-`try/catch` הישן כאן בלע
|
||||||
// את הכשל, וה-run נרשם `succeeded` בלי לעשות כלום — 13,928 ריצות כוזבות.
|
// את הכשל, וה-run נרשם `succeeded` בלי לעשות כלום — 13,928 ריצות כוזבות.
|
||||||
await runJobHandler("sync-case-status", ctx.logger, async () => {
|
await runJobHandler("sync-case-status", ctx.logger, async () => {
|
||||||
const cases = await api.listCases();
|
const cases = await api.listCaseStatuses();
|
||||||
// נקבע מיד — לפני כל קריאת-מארח שעלולה ליפול. אחרת ריצה
|
// נקבע מיד — לפני כל קריאת-מארח שעלולה ליפול. אחרת ריצה
|
||||||
// שנפלה באמצע (או `!companies.length`) הייתה מדווחת scanned=0
|
// שנפלה באמצע (או `!companies.length`) הייתה מדווחת scanned=0
|
||||||
// ומאבדת בדיוק את האבחנה שה-issue הזה נועד לתת.
|
// ומאבדת בדיוק את האבחנה שה-issue הזה נועד לתת.
|
||||||
@@ -1025,9 +1096,9 @@ const plugin = definePlugin({
|
|||||||
|
|
||||||
// כשל-fetch/API אמיתי חייב **לזרוק**, לא `return` בשקט — אחרת
|
// כשל-fetch/API אמיתי חייב **לזרוק**, לא `return` בשקט — אחרת
|
||||||
// ה-run נרשם `succeeded` בלי שקרה כלום (legal-ai issue #637).
|
// ה-run נרשם `succeeded` בלי שקרה כלום (legal-ai issue #637).
|
||||||
let resp: Awaited<ReturnType<typeof ctx.http.fetch>>;
|
let resp: Response;
|
||||||
try {
|
try {
|
||||||
resp = await ctx.http.fetch(`${apiBase}/api/cases/stale?days=30`);
|
resp = await fetchLegalApi(`${apiBase}/api/cases/stale?days=30`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`stale-case-reminder: fetch failed against ${apiBase}: ${String(err)}`,
|
`stale-case-reminder: fetch failed against ${apiBase}: ${String(err)}`,
|
||||||
@@ -1104,7 +1175,7 @@ const plugin = definePlugin({
|
|||||||
// throws CompanyScopeUnavailableError rather than guessing.
|
// throws CompanyScopeUnavailableError rather than guessing.
|
||||||
const apiBase = await resolveApiBase(ctx);
|
const apiBase = await resolveApiBase(ctx);
|
||||||
|
|
||||||
const resp = await ctx.http.fetch(
|
const resp = await fetchLegalApi(
|
||||||
`${apiBase}/api/chair-feedback/weekly-summary`,
|
`${apiBase}/api/chair-feedback/weekly-summary`,
|
||||||
);
|
);
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
@@ -1325,7 +1396,7 @@ const plugin = definePlugin({
|
|||||||
if (!caseNumber) return null;
|
if (!caseNumber) return null;
|
||||||
const apiBase = await resolveApiBase(ctx, companyIdOf(params));
|
const apiBase = await resolveApiBase(ctx, companyIdOf(params));
|
||||||
try {
|
try {
|
||||||
const resp = await ctx.http.fetch(
|
const resp = await fetchLegalApi(
|
||||||
`${apiBase}/api/cases/${encodeURIComponent(caseNumber)}/legal-arguments`,
|
`${apiBase}/api/cases/${encodeURIComponent(caseNumber)}/legal-arguments`,
|
||||||
);
|
);
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
@@ -1362,7 +1433,7 @@ const plugin = definePlugin({
|
|||||||
if (!caseNumber) return [];
|
if (!caseNumber) return [];
|
||||||
const apiBase = await resolveApiBase(ctx, companyIdOf(params));
|
const apiBase = await resolveApiBase(ctx, companyIdOf(params));
|
||||||
try {
|
try {
|
||||||
const resp = await ctx.http.fetch(
|
const resp = await fetchLegalApi(
|
||||||
`${apiBase}/api/cases/${encodeURIComponent(caseNumber)}/precedents`,
|
`${apiBase}/api/cases/${encodeURIComponent(caseNumber)}/precedents`,
|
||||||
);
|
);
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
@@ -1401,7 +1472,7 @@ const plugin = definePlugin({
|
|||||||
const url = new URL(`${apiBase}/api/missing-precedents`);
|
const url = new URL(`${apiBase}/api/missing-precedents`);
|
||||||
url.searchParams.set("case_number", caseNumber);
|
url.searchParams.set("case_number", caseNumber);
|
||||||
url.searchParams.set("status", "open");
|
url.searchParams.set("status", "open");
|
||||||
const resp = await ctx.http.fetch(url.toString());
|
const resp = await fetchLegalApi(url.toString());
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
ctx.logger.warn("legal-case-missing-precedents: API error", {
|
ctx.logger.warn("legal-case-missing-precedents: API error", {
|
||||||
caseNumber,
|
caseNumber,
|
||||||
@@ -1422,13 +1493,13 @@ const plugin = definePlugin({
|
|||||||
|
|
||||||
ctx.data.register("legal-dashboard-stats", async () => {
|
ctx.data.register("legal-dashboard-stats", async () => {
|
||||||
try {
|
try {
|
||||||
const cases = await api.listCases();
|
const cases = await api.listCaseStatuses();
|
||||||
const byStatus: Record<string, number> = {};
|
const byStatus: Record<string, number> = {};
|
||||||
let weekActivity = 0;
|
let weekActivity = 0;
|
||||||
const weekAgoMs = Date.now() - 7 * 24 * 60 * 60 * 1000;
|
const weekAgoMs = Date.now() - 7 * 24 * 60 * 60 * 1000;
|
||||||
for (const c of cases) {
|
for (const c of cases) {
|
||||||
byStatus[c.status] = (byStatus[c.status] ?? 0) + 1;
|
byStatus[c.status] = (byStatus[c.status] ?? 0) + 1;
|
||||||
const updated = (c as { updated_at?: string | null }).updated_at;
|
const updated = c.updated_at;
|
||||||
if (updated) {
|
if (updated) {
|
||||||
const t = Date.parse(updated);
|
const t = Date.parse(updated);
|
||||||
if (!Number.isNaN(t) && t >= weekAgoMs) weekActivity += 1;
|
if (!Number.isNaN(t) && t >= weekAgoMs) weekActivity += 1;
|
||||||
|
|||||||
Reference in New Issue
Block a user